@blackbelt-technology/pi-agent-dashboard 0.5.4 → 0.6.1
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/AGENTS.md +81 -505
- package/README.md +80 -2
- package/docs/AGENTS.md +47 -0
- package/docs/architecture.md +479 -91
- package/package.json +26 -7
- package/packages/extension/AGENTS.md +7 -0
- package/packages/extension/package.json +12 -4
- package/packages/extension/src/AGENTS.md +56 -0
- package/packages/extension/src/__tests__/abort-latch.test.ts +97 -0
- package/packages/extension/src/__tests__/agent-settled.test.ts +82 -0
- package/packages/extension/src/__tests__/artifact-roots.test.ts +83 -0
- package/packages/extension/src/__tests__/ask-user-attachments.test.ts +106 -0
- package/packages/extension/src/__tests__/ask-user-tool.test.ts +90 -27
- package/packages/extension/src/__tests__/auto-session-namer.test.ts +339 -0
- package/packages/extension/src/__tests__/bridge-default-model-apply.test.ts +242 -0
- package/packages/extension/src/__tests__/bridge-default-model-gate.test.ts +6 -3
- package/packages/extension/src/__tests__/bridge-followup-mutation.test.ts +217 -0
- package/packages/extension/src/__tests__/bridge-followup-queue-drain.test.ts +266 -0
- package/packages/extension/src/__tests__/bridge-hasui-flip.test.ts +109 -0
- package/packages/extension/src/__tests__/bridge-no-queue-mutation.test.ts +112 -0
- package/packages/extension/src/__tests__/bridge-plugin-emit-event.test.ts +44 -0
- package/packages/extension/src/__tests__/bridge-shutdown-reset.test.ts +57 -136
- package/packages/extension/src/__tests__/bridge-slash-command-routing.test.ts +7 -7
- package/packages/extension/src/__tests__/bridge-stop-after-turn.test.ts +72 -0
- package/packages/extension/src/__tests__/bridge-system-followup.test.ts +163 -0
- package/packages/extension/src/__tests__/bridge-thinking-level-select.test.ts +68 -0
- package/packages/extension/src/__tests__/browser-skill-registered.test.ts +84 -0
- package/packages/extension/src/__tests__/build-provider-catalogue.test.ts +35 -1
- package/packages/extension/src/__tests__/command-handler.test.ts +331 -35
- package/packages/extension/src/__tests__/commit-draft.test.ts +100 -0
- package/packages/extension/src/__tests__/connection-dropped-frames.test.ts +78 -0
- package/packages/extension/src/__tests__/custom-provider-apikey-roundtrip.test.ts +128 -0
- package/packages/extension/src/__tests__/cwd-missing-probe.test.ts +82 -0
- package/packages/extension/src/__tests__/dashboard-commands-shipped.test.ts +53 -0
- package/packages/extension/src/__tests__/dashboard-context-injector.test.ts +190 -0
- package/packages/extension/src/__tests__/doctor/checks.test.ts +121 -0
- package/packages/extension/src/__tests__/doctor/modules.test.ts +64 -0
- package/packages/extension/src/__tests__/doctor/provenance-hash.test.ts +94 -0
- package/packages/extension/src/__tests__/doctor/router.test.ts +143 -0
- package/packages/extension/src/__tests__/empty-actionable-guard-config.test.ts +32 -0
- package/packages/extension/src/__tests__/empty-actionable-guard.test.ts +73 -0
- package/packages/extension/src/__tests__/enrich-model-metadata.test.ts +21 -0
- package/packages/extension/src/__tests__/extension-slash-command-detection.test.ts +37 -1
- package/packages/extension/src/__tests__/filter-enabled-models.test.ts +151 -0
- package/packages/extension/src/__tests__/fixtures/turn-actionability-fixtures.ts +69 -0
- package/packages/extension/src/__tests__/git-info-status.test.ts +73 -0
- package/packages/extension/src/__tests__/git-poll.test.ts +69 -0
- package/packages/extension/src/__tests__/markdown-image-inliner.test.ts +37 -0
- package/packages/extension/src/__tests__/model-resolve.test.ts +379 -0
- package/packages/extension/src/__tests__/pi-version-tracker.test.ts +109 -0
- package/packages/extension/src/__tests__/process-scanner.test.ts +112 -22
- package/packages/extension/src/__tests__/project-init-detect-stack.test.ts +61 -0
- package/packages/extension/src/__tests__/project-init-dox-kb-config.test.ts +53 -0
- package/packages/extension/src/__tests__/project-init-profiles.test.ts +84 -0
- package/packages/extension/src/__tests__/project-init-scaffold.test.ts +139 -0
- package/packages/extension/src/__tests__/project-init-seed-doctrine.test.ts +100 -0
- package/packages/extension/src/__tests__/project-trust.test.ts +92 -0
- package/packages/extension/src/__tests__/prompt-expander.test.ts +191 -1
- package/packages/extension/src/__tests__/provider-register-reload.test.ts +36 -6
- package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +51 -0
- package/packages/extension/src/__tests__/retry-tracker.test.ts +75 -70
- package/packages/extension/src/__tests__/role-manager.test.ts +585 -0
- package/packages/extension/src/__tests__/role-model-tools-registry-readiness.test.ts +114 -0
- package/packages/extension/src/__tests__/role-model-tools.test.ts +229 -0
- package/packages/extension/src/__tests__/search-files-completeness.test.ts +111 -0
- package/packages/extension/src/__tests__/search-files-ranking.test.ts +168 -0
- package/packages/extension/src/__tests__/server-auto-start.test.ts +121 -4
- package/packages/extension/src/__tests__/server-launcher-launch.test.ts +24 -6
- package/packages/extension/src/__tests__/server-launcher.test.ts +19 -2
- package/packages/extension/src/__tests__/session-sync.test.ts +36 -0
- package/packages/extension/src/__tests__/subagent-frame-buffer.test.ts +239 -0
- package/packages/extension/src/__tests__/tool-result-image-inliner.test.ts +206 -0
- package/packages/extension/src/__tests__/tui-prompt-adapter.test.ts +70 -64
- package/packages/extension/src/__tests__/turn-actionability.test.ts +86 -0
- package/packages/extension/src/__tests__/vcs-info.test.ts +145 -4
- package/packages/extension/src/__tests__/visibility-intent.test.ts +43 -0
- package/packages/extension/src/abort-latch.ts +55 -0
- package/packages/extension/src/abort-latch.ts.AGENTS.md +3 -0
- package/packages/extension/src/agent-settled.ts +72 -0
- package/packages/extension/src/agent-settled.ts.AGENTS.md +3 -0
- package/packages/extension/src/artifact-roots.ts +73 -0
- package/packages/extension/src/artifact-roots.ts.AGENTS.md +3 -0
- package/packages/extension/src/ask-user-attachments.ts +121 -0
- package/packages/extension/src/ask-user-attachments.ts.AGENTS.md +3 -0
- package/packages/extension/src/ask-user-tool.ts +56 -58
- package/packages/extension/src/ask-user-tool.ts.AGENTS.md +3 -0
- package/packages/extension/src/auto-session-namer.ts +334 -0
- package/packages/extension/src/auto-session-namer.ts.AGENTS.md +3 -0
- package/packages/extension/src/bridge-context.ts +86 -8
- package/packages/extension/src/bridge-context.ts.AGENTS.md +3 -0
- package/packages/extension/src/bridge-default-model-gate.ts +22 -6
- package/packages/extension/src/bridge-default-model-gate.ts.AGENTS.md +3 -0
- package/packages/extension/src/bridge.ts +1241 -360
- package/packages/extension/src/bridge.ts.AGENTS.md +3 -0
- package/packages/extension/src/canvas-tool.ts +107 -0
- package/packages/extension/src/command-handler.ts +490 -51
- package/packages/extension/src/command-handler.ts.AGENTS.md +3 -0
- package/packages/extension/src/commit-draft-agent.ts +114 -0
- package/packages/extension/src/commit-draft-agent.ts.AGENTS.md +3 -0
- package/packages/extension/src/commit-draft.ts +136 -0
- package/packages/extension/src/commit-draft.ts.AGENTS.md +3 -0
- package/packages/extension/src/connection.ts +32 -1
- package/packages/extension/src/connection.ts.AGENTS.md +3 -0
- package/packages/extension/src/dashboard-context-injector.ts +124 -0
- package/packages/extension/src/dashboard-context-injector.ts.AGENTS.md +3 -0
- package/packages/extension/src/dashboard-default-adapter.ts.AGENTS.md +3 -0
- package/packages/extension/src/dev-build.ts.AGENTS.md +3 -0
- package/packages/extension/src/empty-actionable-guard-config.ts +32 -0
- package/packages/extension/src/empty-actionable-guard-config.ts.AGENTS.md +3 -0
- package/packages/extension/src/empty-actionable-guard.ts +90 -0
- package/packages/extension/src/empty-actionable-guard.ts.AGENTS.md +3 -0
- package/packages/extension/src/event-forwarder.ts.AGENTS.md +3 -0
- package/packages/extension/src/flow-event-wiring.ts +4 -14
- package/packages/extension/src/flow-event-wiring.ts.AGENTS.md +3 -0
- package/packages/extension/src/git-link-builder.ts.AGENTS.md +3 -0
- package/packages/extension/src/git-poll.ts +38 -0
- package/packages/extension/src/git-poll.ts.AGENTS.md +3 -0
- package/packages/extension/src/hasui-flip.ts +56 -0
- package/packages/extension/src/hasui-flip.ts.AGENTS.md +3 -0
- package/packages/extension/src/markdown-image-inliner.ts +45 -2
- package/packages/extension/src/markdown-image-inliner.ts.AGENTS.md +3 -0
- package/packages/extension/src/model-tracker.ts +145 -19
- package/packages/extension/src/model-tracker.ts.AGENTS.md +3 -0
- package/packages/extension/src/multiselect-decode.ts.AGENTS.md +3 -0
- package/packages/extension/src/multiselect-list.ts.AGENTS.md +3 -0
- package/packages/extension/src/multiselect-polyfill.ts.AGENTS.md +3 -0
- package/packages/extension/src/process-metrics.ts.AGENTS.md +3 -0
- package/packages/extension/src/process-scanner.ts +114 -103
- package/packages/extension/src/process-scanner.ts.AGENTS.md +3 -0
- package/packages/extension/src/project-init/AGENTS.md +12 -0
- package/packages/extension/src/project-init/detect-stack.ts +146 -0
- package/packages/extension/src/project-init/dox-kb-config.ts +47 -0
- package/packages/extension/src/project-init/profiles.ts +135 -0
- package/packages/extension/src/project-init/scaffold.ts +192 -0
- package/packages/extension/src/project-init/seed-doctrine.ts +95 -0
- package/packages/extension/src/project-trust.ts +63 -0
- package/packages/extension/src/project-trust.ts.AGENTS.md +3 -0
- package/packages/extension/src/prompt-bus.ts +10 -1
- package/packages/extension/src/prompt-bus.ts.AGENTS.md +3 -0
- package/packages/extension/src/prompt-expander.ts +238 -37
- package/packages/extension/src/prompt-expander.ts.AGENTS.md +3 -0
- package/packages/extension/src/provider-register.ts +323 -54
- package/packages/extension/src/provider-register.ts.AGENTS.md +3 -0
- package/packages/extension/src/retry-tracker.ts +64 -39
- package/packages/extension/src/retry-tracker.ts.AGENTS.md +3 -0
- package/packages/extension/src/role-manager.ts +436 -0
- package/packages/extension/src/role-manager.ts.AGENTS.md +3 -0
- package/packages/extension/src/role-model-tools.ts +301 -0
- package/packages/extension/src/role-model-tools.ts.AGENTS.md +3 -0
- package/packages/extension/src/server-auto-start.ts +59 -23
- package/packages/extension/src/server-auto-start.ts.AGENTS.md +3 -0
- package/packages/extension/src/server-launcher.ts +56 -16
- package/packages/extension/src/server-launcher.ts.AGENTS.md +3 -0
- package/packages/extension/src/session-sync.ts +111 -15
- package/packages/extension/src/session-sync.ts.AGENTS.md +3 -0
- package/packages/extension/src/slash-dispatch.ts +13 -11
- package/packages/extension/src/slash-dispatch.ts.AGENTS.md +3 -0
- package/packages/extension/src/source-detector.ts.AGENTS.md +3 -0
- package/packages/extension/src/subagent-frame-buffer.ts +220 -0
- package/packages/extension/src/subagent-frame-buffer.ts.AGENTS.md +3 -0
- package/packages/extension/src/tool-result-image-inliner.ts +204 -0
- package/packages/extension/src/tool-result-image-inliner.ts.AGENTS.md +3 -0
- package/packages/extension/src/tui-prompt-adapter.ts +123 -0
- package/packages/extension/src/tui-prompt-adapter.ts.AGENTS.md +3 -0
- package/packages/extension/src/turn-actionability.ts +117 -0
- package/packages/extension/src/turn-actionability.ts.AGENTS.md +3 -0
- package/packages/extension/src/ui-modules.ts.AGENTS.md +3 -0
- package/packages/extension/src/vcs-info.ts +91 -129
- package/packages/extension/src/vcs-info.ts.AGENTS.md +3 -0
- package/packages/extension/src/visibility-intent.ts +34 -0
- package/packages/extension/src/visibility-intent.ts.AGENTS.md +3 -0
- package/packages/extension/tsconfig.json +0 -3
- package/packages/server/AGENTS.md +7 -0
- package/packages/server/package.json +21 -9
- package/packages/server/src/AGENTS.md +20 -0
- package/packages/server/src/__tests__/active-sessions-in-cwd.test.ts +97 -0
- package/packages/server/src/__tests__/attach-proposal-replay.test.ts +92 -0
- package/packages/server/src/__tests__/auth-plugin.test.ts +3 -3
- package/packages/server/src/__tests__/auth.test.ts +1 -1
- package/packages/server/src/__tests__/auto-attach-slug-defense.test.ts +6 -9
- package/packages/server/src/__tests__/auto-attach.test.ts +12 -18
- package/packages/server/src/__tests__/auto-resume.test.ts +2 -2
- package/packages/server/src/__tests__/auto-shutdown.test.ts +6 -14
- package/packages/server/src/__tests__/automation-session-close.test.ts +73 -0
- package/packages/server/src/__tests__/bearer-auth.test.ts +67 -0
- package/packages/server/src/__tests__/boot-parent-liveness.test.ts +48 -0
- package/packages/server/src/__tests__/browser-gateway-broadcast-serialize-once.test.ts +144 -0
- package/packages/server/src/__tests__/browser-gateway-dropped-frames.test.ts +96 -0
- package/packages/server/src/__tests__/browser-gateway-handler-errors.test.ts +6 -6
- package/packages/server/src/__tests__/browser-gateway-load.test.ts +233 -0
- package/packages/server/src/__tests__/browser-gateway-plugin-action-fanout.test.ts +113 -0
- package/packages/server/src/__tests__/browser-gateway-register-handler.test.ts +1 -1
- package/packages/server/src/__tests__/browser-gateway-role-remove.test.ts +68 -0
- package/packages/server/src/__tests__/browser-gateway-snapshot-on-connect.test.ts +49 -5
- package/packages/server/src/__tests__/build-auth-status.test.ts +2 -2
- package/packages/server/src/__tests__/canvas-accumulator.test.ts +187 -0
- package/packages/server/src/__tests__/canvas-settings.test.ts +68 -0
- package/packages/server/src/__tests__/changelog-fs.test.ts +61 -1
- package/packages/server/src/__tests__/changelog-parser.test.ts +2 -2
- package/packages/server/src/__tests__/changelog-remote.test.ts +1 -1
- package/packages/server/src/__tests__/cli-parse.test.ts +56 -2
- package/packages/server/src/__tests__/cold-boot-openspec-broadcast.test.ts +1 -1
- package/packages/server/src/__tests__/cold-start-recovery-exempt.test.ts +94 -0
- package/packages/server/src/__tests__/commit-draft-relay.test.ts +61 -0
- package/packages/server/src/__tests__/config-api.test.ts +7 -0
- package/packages/server/src/__tests__/cors.test.ts +78 -41
- package/packages/server/src/__tests__/csp.test.ts +71 -0
- package/packages/server/src/__tests__/cwd-missing-handling.test.ts +101 -0
- package/packages/server/src/__tests__/dashboard-source-decision.test.ts +156 -0
- package/packages/server/src/__tests__/directory-service-eventloop-turns.test.ts +211 -0
- package/packages/server/src/__tests__/directory-service-folderhead-async.test.ts +145 -0
- package/packages/server/src/__tests__/directory-service-known-dirs.test.ts +125 -0
- package/packages/server/src/__tests__/directory-service-openspec-enabled.test.ts +23 -8
- package/packages/server/src/__tests__/directory-service-pending-emit.test.ts +226 -0
- package/packages/server/src/__tests__/directory-service-refresh-force.test.ts +21 -6
- package/packages/server/src/__tests__/directory-service-specs-mtime.test.ts +39 -12
- package/packages/server/src/__tests__/directory-service-toctou.test.ts +55 -46
- package/packages/server/src/__tests__/directory-service-watcher-dedup.test.ts +166 -0
- package/packages/server/src/__tests__/directory-service.test.ts +39 -22
- package/packages/server/src/__tests__/dispatch-extension-command-router.test.ts +1 -1
- package/packages/server/src/__tests__/doctor-route.test.ts +145 -1
- package/packages/server/src/__tests__/draining-ws.test.ts +131 -0
- package/packages/server/src/__tests__/eml-cache.test.ts +60 -0
- package/packages/server/src/__tests__/event-status-extraction.test.ts +1 -1
- package/packages/server/src/__tests__/event-wiring-is-git-repo.test.ts +128 -0
- package/packages/server/src/__tests__/event-wiring-process-classify.test.ts +122 -0
- package/packages/server/src/__tests__/event-wiring-providers-list.test.ts +9 -11
- package/packages/server/src/__tests__/event-wiring-queue-state.test.ts +8 -10
- package/packages/server/src/__tests__/event-wiring-resume-clear.test.ts +6 -8
- package/packages/server/src/__tests__/event-wiring-roles-list-builtin.test.ts +90 -0
- package/packages/server/src/__tests__/event-wiring-source-stamp.test.ts +180 -0
- package/packages/server/src/__tests__/event-wiring-worktree-rekey.test.ts +157 -0
- package/packages/server/src/__tests__/eventloop-sampler.test.ts +111 -0
- package/packages/server/src/__tests__/eventloop-spike-metrics.test.ts +60 -0
- package/packages/server/src/__tests__/faux-echo-system-context.unit.test.ts +31 -0
- package/packages/server/src/__tests__/faux-router.unit.test.ts +71 -0
- package/packages/server/src/__tests__/faux-session.integration.test.ts +316 -0
- package/packages/server/src/__tests__/file-absolute-containment.test.ts +224 -0
- package/packages/server/src/__tests__/file-artifact-serving.test.ts +189 -0
- package/packages/server/src/__tests__/file-kind-endpoint.test.ts +133 -0
- package/packages/server/src/__tests__/file-raw-render-endpoints.test.ts +936 -0
- package/packages/server/src/__tests__/file-tree-endpoint.test.ts +90 -0
- package/packages/server/src/__tests__/file-watch-manager.test.ts +88 -0
- package/packages/server/src/__tests__/file-write-endpoint.test.ts +222 -0
- package/packages/server/src/__tests__/folder-head-integration.test.ts +83 -0
- package/packages/server/src/__tests__/folder-head-poll.test.ts +167 -0
- package/packages/server/src/__tests__/folder-head-watcher.test.ts +133 -0
- package/packages/server/src/__tests__/fork-empty-session-preflight.test.ts +2 -2
- package/packages/server/src/__tests__/fork-jsonl-roundtrip.test.ts +1 -1
- package/packages/server/src/__tests__/genuine-local.test.ts +96 -0
- package/packages/server/src/__tests__/git-commit-operations.test.ts +153 -0
- package/packages/server/src/__tests__/git-operations.test.ts +66 -7
- package/packages/server/src/__tests__/git-pr-operations.test.ts +299 -0
- package/packages/server/src/__tests__/git-worktree-compose.test.ts +57 -0
- package/packages/server/src/__tests__/git-worktree-lifecycle-ops.test.ts +363 -0
- package/packages/server/src/__tests__/git-worktree-lifecycle-routes.test.ts +322 -0
- package/packages/server/src/__tests__/git-worktree-lifecycle.test.ts +161 -0
- package/packages/server/src/__tests__/git-worktree-ops.test.ts +263 -0
- package/packages/server/src/__tests__/git-worktree-routes.test.ts +342 -0
- package/packages/server/src/__tests__/git-worktree.test.ts +395 -0
- package/packages/server/src/__tests__/goal-budget-guard.test.ts +32 -0
- package/packages/server/src/__tests__/goal-routes.test.ts +247 -0
- package/packages/server/src/__tests__/goal-session-primer.test.ts +53 -0
- package/packages/server/src/__tests__/goal-status-projector.test.ts +133 -0
- package/packages/server/src/__tests__/goal-store.test.ts +364 -0
- package/packages/server/src/__tests__/goal-supervisor.test.ts +321 -0
- package/packages/server/src/__tests__/goal-verdict-accumulator.test.ts +90 -0
- package/packages/server/src/__tests__/grep.test.ts +95 -0
- package/packages/server/src/__tests__/headless-pid-registry-goal-id.test.ts +71 -0
- package/packages/server/src/__tests__/headless-pid-registry-kill-by-token.test.ts +107 -0
- package/packages/server/src/__tests__/headless-pid-registry-kill-escalation.test.ts +163 -0
- package/packages/server/src/__tests__/headless-pid-registry.test.ts +57 -49
- package/packages/server/src/__tests__/headless-shutdown-fallback.test.ts +16 -13
- package/packages/server/src/__tests__/health-compatibility.test.ts +81 -0
- package/packages/server/src/__tests__/health-endpoint.test.ts +8 -2
- package/packages/server/src/__tests__/health-shape.test.ts +63 -0
- package/packages/server/src/__tests__/heartbeat-ack.test.ts +2 -2
- package/packages/server/src/__tests__/helpers/draining-ws.ts +170 -0
- package/packages/server/src/__tests__/helpers/load-fixtures.ts +152 -0
- package/packages/server/src/__tests__/hide-unhide-placement.test.ts +88 -0
- package/packages/server/src/__tests__/home-lock-release.test.ts +1 -1
- package/packages/server/src/__tests__/hydration-metrics.test.ts +62 -0
- package/packages/server/src/__tests__/identity.test.ts +79 -0
- package/packages/server/src/__tests__/idle-timer-respects-terminals.test.ts +2 -3
- package/packages/server/src/__tests__/inline-terminal-handler.test.ts +73 -0
- package/packages/server/src/__tests__/installed-package-enricher.test.ts +7 -7
- package/packages/server/src/__tests__/internal-registry.test.ts +76 -0
- package/packages/server/src/__tests__/is-activity-event.test.ts +1 -1
- package/packages/server/src/__tests__/is-unread-trigger.test.ts +1 -1
- package/packages/server/src/__tests__/json-store.test.ts +1 -1
- package/packages/server/src/__tests__/keeper-manager.test.ts +34 -0
- package/packages/server/src/__tests__/last-activity-broadcast.test.ts +8 -10
- package/packages/server/src/__tests__/launch-source-effective.test.ts +39 -0
- package/packages/server/src/__tests__/live-server-endpoint.test.ts +134 -0
- package/packages/server/src/__tests__/liveness-stamp-wiring.test.ts +144 -0
- package/packages/server/src/__tests__/localhost-guard.test.ts +24 -1
- package/packages/server/src/__tests__/memory-event-store.test.ts +320 -2
- package/packages/server/src/__tests__/memory-session-manager.test.ts +76 -1
- package/packages/server/src/__tests__/meta-persistence.test.ts +138 -1
- package/packages/server/src/__tests__/migrate-persistence.test.ts +1 -1
- package/packages/server/src/__tests__/model-proxy-diagnostics-routes.test.ts +64 -0
- package/packages/server/src/__tests__/model-proxy-routes.test.ts +174 -12
- package/packages/server/src/__tests__/models-introspection-routes.test.ts +107 -0
- package/packages/server/src/__tests__/node-guard.test.ts +96 -7
- package/packages/server/src/__tests__/npm-search-proxy.test.ts +29 -1
- package/packages/server/src/__tests__/oauth-callback-server.test.ts +21 -5
- package/packages/server/src/__tests__/office-preview.test.ts +198 -0
- package/packages/server/src/__tests__/openspec-archive.test.ts +1 -1
- package/packages/server/src/__tests__/openspec-change-order-store.test.ts +62 -0
- package/packages/server/src/__tests__/openspec-change-watcher-debounce.test.ts +112 -0
- package/packages/server/src/__tests__/openspec-change-watcher-filter.test.ts +45 -0
- package/packages/server/src/__tests__/openspec-change-watcher-fs.test.ts +142 -0
- package/packages/server/src/__tests__/openspec-connect-snapshot.test.ts +1 -1
- package/packages/server/src/__tests__/openspec-group-broadcast.test.ts +1 -1
- package/packages/server/src/__tests__/openspec-group-join.test.ts +1 -1
- package/packages/server/src/__tests__/openspec-group-routes.test.ts +1 -1
- package/packages/server/src/__tests__/openspec-group-store.test.ts +1 -1
- package/packages/server/src/__tests__/openspec-poll-worker.test.ts +220 -0
- package/packages/server/src/__tests__/openspec-profile-routes.test.ts +415 -0
- package/packages/server/src/__tests__/openspec-tasks-parser.test.ts +1 -1
- package/packages/server/src/__tests__/package-manager-wrapper-move.test.ts +1 -1
- package/packages/server/src/__tests__/package-manager-wrapper-reset.test.ts +194 -0
- package/packages/server/src/__tests__/package-manager-wrapper-resolve.test.ts +13 -3
- package/packages/server/src/__tests__/package-manager-wrapper.test.ts +1 -1
- package/packages/server/src/__tests__/package-routes.test.ts +103 -8
- package/packages/server/src/__tests__/package-source-helpers.test.ts +1 -1
- package/packages/server/src/__tests__/paired-devices.test.ts +59 -0
- package/packages/server/src/__tests__/pairing.test.ts +191 -0
- package/packages/server/src/__tests__/pending-attach-registry.test.ts +1 -1
- package/packages/server/src/__tests__/pending-automation-run-registry.test.ts +54 -0
- package/packages/server/src/__tests__/pending-fork-registry.test.ts +1 -1
- package/packages/server/src/__tests__/pending-initial-prompt-registry.test.ts +52 -0
- package/packages/server/src/__tests__/pending-load-manager.test.ts +1 -1
- package/packages/server/src/__tests__/pending-resume-intent-registry.test.ts +1 -1
- package/packages/server/src/__tests__/pending-resume-registry.test.ts +1 -1
- package/packages/server/src/__tests__/pending-worktree-base-registry.test.ts +97 -0
- package/packages/server/src/__tests__/pi-changelog-integration.test.ts +6 -6
- package/packages/server/src/__tests__/pi-changelog-routes.test.ts +16 -4
- package/packages/server/src/__tests__/pi-core-checker.test.ts +2 -2
- package/packages/server/src/__tests__/pi-core-routes.test.ts +1 -1
- package/packages/server/src/__tests__/pi-core-updater-managed-path.test.ts +1 -1
- package/packages/server/src/__tests__/pi-core-updater.test.ts +2 -2
- package/packages/server/src/__tests__/pi-dev-version-check.test.ts +1 -1
- package/packages/server/src/__tests__/pi-gateway-bind-host.test.ts +81 -0
- package/packages/server/src/__tests__/pi-gateway-consume-pending-attach.test.ts +7 -4
- package/packages/server/src/__tests__/pi-resource-scanner.test.ts +137 -3
- package/packages/server/src/__tests__/pi-version-skew.test.ts +22 -1
- package/packages/server/src/__tests__/pi-version-update-handling.test.ts +51 -0
- package/packages/server/src/__tests__/plugin-intent-cache.test.ts +4 -4
- package/packages/server/src/__tests__/preferences-store.test.ts +312 -3
- package/packages/server/src/__tests__/process-classifier.test.ts +104 -0
- package/packages/server/src/__tests__/process-manager-codes.test.ts +1 -1
- package/packages/server/src/__tests__/process-manager-keeper-spawn.test.ts +77 -24
- package/packages/server/src/__tests__/process-manager-managed-path.test.ts +1 -1
- package/packages/server/src/__tests__/process-manager.test.ts +1 -1
- package/packages/server/src/__tests__/proposal-attach-naming.test.ts +1 -1
- package/packages/server/src/__tests__/provider-auth-handlers.test.ts +3 -19
- package/packages/server/src/__tests__/provider-auth-routes.test.ts +12 -5
- package/packages/server/src/__tests__/provider-auth-storage.test.ts +22 -17
- package/packages/server/src/__tests__/provider-catalogue-cache.test.ts +1 -1
- package/packages/server/src/__tests__/provider-probe.test.ts +1 -1
- package/packages/server/src/__tests__/provider-routes-masked-key.test.ts +110 -0
- package/packages/server/src/__tests__/reattach-placement.test.ts +21 -7
- package/packages/server/src/__tests__/recommended-routes.test.ts +53 -11
- package/packages/server/src/__tests__/reconcile-session-order.test.ts +71 -0
- package/packages/server/src/__tests__/recovery-dedupe-and-lock.test.ts +40 -0
- package/packages/server/src/__tests__/recovery-e2e.test.ts +191 -0
- package/packages/server/src/__tests__/recovery-offer.test.ts +192 -0
- package/packages/server/src/__tests__/recovery-server.test.ts +7 -12
- package/packages/server/src/__tests__/replace-proposal-race.test.ts +236 -0
- package/packages/server/src/__tests__/replay-truncate.test.ts +61 -0
- package/packages/server/src/__tests__/resolve-mention-endpoint.test.ts +153 -0
- package/packages/server/src/__tests__/resolve-order-key.test.ts +31 -0
- package/packages/server/src/__tests__/resolve-published-variant.test.ts +133 -0
- package/packages/server/src/__tests__/resource-activation-routes.test.ts +151 -0
- package/packages/server/src/__tests__/resource-activation-toggle.test.ts +153 -0
- package/packages/server/src/__tests__/restart-helper.test.ts +92 -5
- package/packages/server/src/__tests__/retire-view-message-surface.test.ts +35 -0
- package/packages/server/src/__tests__/ring-buffer.test.ts +1 -1
- package/packages/server/src/__tests__/routes-git-worktree-init.test.ts +464 -0
- package/packages/server/src/__tests__/server-pid.test.ts +1 -1
- package/packages/server/src/__tests__/session-action-handler-followup-queue.test.ts +163 -0
- package/packages/server/src/__tests__/session-action-handler-headless-reload.test.ts +3 -3
- package/packages/server/src/__tests__/session-action-handler-spawn-error.test.ts +5 -5
- package/packages/server/src/__tests__/session-action-handler-spawn-with-attach.test.ts +2 -2
- package/packages/server/src/__tests__/session-action-handler-spawn-with-initial-prompt.test.ts +80 -0
- package/packages/server/src/__tests__/session-action-handler-spawn.test.ts +8 -8
- package/packages/server/src/__tests__/session-api.test.ts +9 -7
- package/packages/server/src/__tests__/session-card-ordering-gates.test.ts +160 -0
- package/packages/server/src/__tests__/session-diff.test.ts +719 -5
- package/packages/server/src/__tests__/session-discovery-skill-firstmessage.test.ts +2 -2
- package/packages/server/src/__tests__/session-file-reader.test.ts +89 -4
- package/packages/server/src/__tests__/session-kill-e2e.test.ts +245 -0
- package/packages/server/src/__tests__/session-lifecycle-logging.test.ts +2 -2
- package/packages/server/src/__tests__/session-load-worker.test.ts +175 -0
- package/packages/server/src/__tests__/session-name-provenance-persistence.test.ts +74 -0
- package/packages/server/src/__tests__/session-order-manager.test.ts +71 -3
- package/packages/server/src/__tests__/session-order-reboot.test.ts +22 -7
- package/packages/server/src/__tests__/session-ordering-integration.test.ts +18 -4
- package/packages/server/src/__tests__/session-routes-tool-result.test.ts +134 -0
- package/packages/server/src/__tests__/session-scanner-resolve-dir.integration.test.ts +96 -0
- package/packages/server/src/__tests__/session-scanner.test.ts +96 -4
- package/packages/server/src/__tests__/session-tags-persistence.test.ts +85 -0
- package/packages/server/src/__tests__/shutdown-endpoint.test.ts +6 -5
- package/packages/server/src/__tests__/skip-wipe.test.ts +2 -2
- package/packages/server/src/__tests__/sleep-aware-heartbeat.test.ts +2 -2
- package/packages/server/src/__tests__/spa-fallback.test.ts +10 -8
- package/packages/server/src/__tests__/spawn-correlation-token-integration.test.ts +3 -3
- package/packages/server/src/__tests__/spawn-env-electron-parity.test.ts +47 -0
- package/packages/server/src/__tests__/spawn-failure-log.test.ts +2 -2
- package/packages/server/src/__tests__/spawn-preflight.test.ts +1 -1
- package/packages/server/src/__tests__/spawn-register-watchdog.test.ts +2 -2
- package/packages/server/src/__tests__/spawn-token.test.ts +34 -3
- package/packages/server/src/__tests__/spawned-turn-log.test.ts +88 -0
- package/packages/server/src/__tests__/subscription-handler.test.ts +114 -5
- package/packages/server/src/__tests__/system-open-endpoints.test.ts +150 -0
- package/packages/server/src/__tests__/system-routes-restart.test.ts +55 -1
- package/packages/server/src/__tests__/system-routes-spawn-failures.test.ts +2 -2
- package/packages/server/src/__tests__/terminal-gateway.test.ts +3 -2
- package/packages/server/src/__tests__/terminal-manager.test.ts +15 -1
- package/packages/server/src/__tests__/test-server-canary.test.ts +67 -0
- package/packages/server/src/__tests__/tool-routes.test.ts +28 -1
- package/packages/server/src/__tests__/translate-path-source.test.ts +1 -1
- package/packages/server/src/__tests__/tunnel-block-events.test.ts +74 -0
- package/packages/server/src/__tests__/tunnel-cleanup.test.ts +1 -1
- package/packages/server/src/__tests__/tunnel-config-redaction.test.ts +68 -0
- package/packages/server/src/__tests__/tunnel-enroll.test.ts +105 -0
- package/packages/server/src/__tests__/tunnel-kind-gate.test.ts +48 -0
- package/packages/server/src/__tests__/tunnel-ngrok.test.ts +101 -0
- package/packages/server/src/__tests__/tunnel-tailscale.test.ts +99 -0
- package/packages/server/src/__tests__/tunnel-watchdog.test.ts +1 -1
- package/packages/server/src/__tests__/tunnel-zerotier.test.ts +91 -0
- package/packages/server/src/__tests__/tunnel-zrok-v2.test.ts +319 -0
- package/packages/server/src/__tests__/tunnel.test.ts +31 -19
- package/packages/server/src/__tests__/ui-decorators-replay.test.ts +2 -2
- package/packages/server/src/__tests__/ui-modules-replay.test.ts +2 -2
- package/packages/server/src/__tests__/unread-trigger-wiring.test.ts +8 -10
- package/packages/server/src/__tests__/viewed-session-tracker.test.ts +1 -1
- package/packages/server/src/__tests__/worktree-base-spawn-flow.test.ts +157 -0
- package/packages/server/src/__tests__/worktree-init-errors.test.ts +72 -0
- package/packages/server/src/__tests__/worktree-init-registry.test.ts +178 -0
- package/packages/server/src/__tests__/worktree-init-trust.test.ts +105 -0
- package/packages/server/src/__tests__/worktree-init.test.ts +214 -0
- package/packages/server/src/__tests__/worktree-pi-settings-rewrite.test.ts +207 -0
- package/packages/server/src/__tests__/ws-ping-pong.test.ts +2 -2
- package/packages/server/src/__tests__/ws-ticket.test.ts +58 -0
- package/packages/server/src/__tests__/ws-upgrade-routing.test.ts +160 -0
- package/packages/server/src/__tests__/wsl-tmux-probe-cache.test.ts +2 -2
- package/packages/server/src/auth/AGENTS.md +21 -0
- package/packages/server/src/{auth-plugin.ts → auth/auth-plugin.ts} +46 -7
- package/packages/server/src/auth/auth-plugin.ts.AGENTS.md +3 -0
- package/packages/server/src/{auth.ts → auth/auth.ts} +1 -1
- package/packages/server/src/auth/auth.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/bearer-auth.ts +47 -0
- package/packages/server/src/auth/bearer-auth.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/cors-origin.ts +74 -0
- package/packages/server/src/auth/cors-origin.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/csp.ts +65 -0
- package/packages/server/src/auth/csp.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/identity.ts +104 -0
- package/packages/server/src/auth/identity.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/local-token.ts +63 -0
- package/packages/server/src/auth/local-token.ts.AGENTS.md +3 -0
- package/packages/server/src/{localhost-guard.ts → auth/localhost-guard.ts} +68 -4
- package/packages/server/src/auth/localhost-guard.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/node-guard.ts +72 -0
- package/packages/server/src/auth/node-guard.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/oauth-callback-server.ts.AGENTS.md +3 -0
- package/packages/server/src/{provider-auth-handlers.ts → auth/provider-auth-handlers.ts} +0 -157
- package/packages/server/src/auth/provider-auth-handlers.ts.AGENTS.md +3 -0
- package/packages/server/src/{provider-auth-storage.ts → auth/provider-auth-storage.ts} +1 -1
- package/packages/server/src/auth/provider-auth-storage.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/spawn-token.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/test-env-guard.ts.AGENTS.md +3 -0
- package/packages/server/src/auth/ws-ticket.ts +111 -0
- package/packages/server/src/auth/ws-ticket.ts.AGENTS.md +3 -0
- package/packages/server/src/browse.ts.AGENTS.md +3 -0
- package/packages/server/src/browser-handlers/AGENTS.md +13 -0
- package/packages/server/src/browser-handlers/__tests__/session-action-handler.test.ts +49 -0
- package/packages/server/src/browser-handlers/__tests__/session-action-liveness-clear.test.ts +75 -0
- package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +144 -8
- package/packages/server/src/browser-handlers/directory-handler.ts +18 -0
- package/packages/server/src/browser-handlers/handler-context.ts +43 -12
- package/packages/server/src/browser-handlers/session-action-handler.ts +105 -66
- package/packages/server/src/browser-handlers/session-action-helpers.ts +1 -1
- package/packages/server/src/browser-handlers/session-meta-handler.ts +182 -2
- package/packages/server/src/browser-handlers/subscription-handler.ts +44 -5
- package/packages/server/src/browser-handlers/terminal-handler.ts +47 -0
- package/packages/server/src/canvas/AGENTS.md +8 -0
- package/packages/server/src/canvas/canvas-accumulator.ts +183 -0
- package/packages/server/src/canvas/canvas-settings.ts +115 -0
- package/packages/server/src/changelog/AGENTS.md +9 -0
- package/packages/server/src/{changelog-fs.ts → changelog/changelog-fs.ts} +93 -0
- package/packages/server/src/changelog/changelog-fs.ts.AGENTS.md +3 -0
- package/packages/server/src/changelog/changelog-parser.ts.AGENTS.md +3 -0
- package/packages/server/src/changelog/changelog-remote.ts.AGENTS.md +3 -0
- package/packages/server/src/cli.ts +15 -5
- package/packages/server/src/cli.ts.AGENTS.md +3 -0
- package/packages/server/src/commit-draft-relay.ts +88 -0
- package/packages/server/src/commit-draft-relay.ts.AGENTS.md +3 -0
- package/packages/server/src/config-api.ts +47 -5
- package/packages/server/src/config-api.ts.AGENTS.md +3 -0
- package/packages/server/src/directory-service.ts +588 -106
- package/packages/server/src/directory-service.ts.AGENTS.md +3 -0
- package/packages/server/src/event-wiring.ts +792 -64
- package/packages/server/src/event-wiring.ts.AGENTS.md +3 -0
- package/packages/server/src/file-watch-manager.ts +122 -0
- package/packages/server/src/fix-pty-permissions.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/AGENTS.md +16 -0
- package/packages/server/src/git-worktree/folder-head-poll.ts +175 -0
- package/packages/server/src/git-worktree/folder-head-poll.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/folder-head-watcher.ts +169 -0
- package/packages/server/src/git-worktree/folder-head-watcher.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/git-operations.ts +1687 -0
- package/packages/server/src/git-worktree/git-operations.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/git-worktree-compose.ts +47 -0
- package/packages/server/src/git-worktree/git-worktree-compose.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/git-worktree-lifecycle.ts +148 -0
- package/packages/server/src/git-worktree/git-worktree-lifecycle.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/git-worktree.ts +172 -0
- package/packages/server/src/git-worktree/git-worktree.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/worktree-init-errors.ts +60 -0
- package/packages/server/src/git-worktree/worktree-init-errors.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/worktree-init-registry.ts +244 -0
- package/packages/server/src/git-worktree/worktree-init-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +96 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts.AGENTS.md +3 -0
- package/packages/server/src/git-worktree/worktree-init.ts +423 -0
- package/packages/server/src/git-worktree/worktree-init.ts.AGENTS.md +3 -0
- package/packages/server/src/goal/AGENTS.md +12 -0
- package/packages/server/src/goal/goal-budget-guard.ts +42 -0
- package/packages/server/src/goal/goal-budget-guard.ts.AGENTS.md +3 -0
- package/packages/server/src/goal/goal-session-primer.ts +99 -0
- package/packages/server/src/goal/goal-session-primer.ts.AGENTS.md +3 -0
- package/packages/server/src/goal/goal-status-projector.ts +121 -0
- package/packages/server/src/goal/goal-status-projector.ts.AGENTS.md +3 -0
- package/packages/server/src/goal/goal-store.ts +530 -0
- package/packages/server/src/goal/goal-store.ts.AGENTS.md +3 -0
- package/packages/server/src/goal/goal-supervisor.ts +445 -0
- package/packages/server/src/goal/goal-supervisor.ts.AGENTS.md +3 -0
- package/packages/server/src/goal/goal-verdict-accumulator.ts +101 -0
- package/packages/server/src/goal/goal-verdict-accumulator.ts.AGENTS.md +3 -0
- package/packages/server/src/home-lock.js.AGENTS.md +3 -0
- package/packages/server/src/lib/AGENTS.md +16 -0
- package/packages/server/src/lib/__tests__/md-candidates.test.ts +81 -0
- package/packages/server/src/lib/__tests__/path-containment.test.ts +119 -0
- package/packages/server/src/lib/__tests__/resolve-file-mention.test.ts +87 -0
- package/packages/server/src/lib/__tests__/writable-md-target.test.ts +112 -0
- package/packages/server/src/lib/artifact-roots.ts +76 -0
- package/packages/server/src/lib/decode-file-uri.ts +18 -0
- package/packages/server/src/lib/eml.ts +259 -0
- package/packages/server/src/lib/grep.ts +257 -0
- package/packages/server/src/lib/md-candidates.ts +104 -0
- package/packages/server/src/lib/mime-types.ts +29 -0
- package/packages/server/src/lib/office-preview.ts +381 -0
- package/packages/server/src/lib/path-containment.ts +123 -0
- package/packages/server/src/lib/resolve-file-mention.ts +85 -0
- package/packages/server/src/lib/writable-md-target.ts +97 -0
- package/packages/server/src/lifecycle/AGENTS.md +12 -0
- package/packages/server/src/lifecycle/boot-parent-liveness.ts +159 -0
- package/packages/server/src/lifecycle/boot-parent-liveness.ts.AGENTS.md +3 -0
- package/packages/server/src/lifecycle/dashboard-source-decision.ts +97 -0
- package/packages/server/src/lifecycle/dashboard-source-decision.ts.AGENTS.md +3 -0
- package/packages/server/src/lifecycle/home-lock-release.ts.AGENTS.md +3 -0
- package/packages/server/src/lifecycle/home-lock.ts.AGENTS.md +3 -0
- package/packages/server/src/lifecycle/launch-source-effective.ts +41 -0
- package/packages/server/src/lifecycle/launch-source-effective.ts.AGENTS.md +3 -0
- package/packages/server/src/{recovery-server.ts → lifecycle/recovery-server.ts} +13 -12
- package/packages/server/src/lifecycle/recovery-server.ts.AGENTS.md +3 -0
- package/packages/server/src/live-server/AGENTS.md +8 -0
- package/packages/server/src/live-server/live-server-manager.ts +84 -0
- package/packages/server/src/live-server/live-server-manager.ts.AGENTS.md +3 -0
- package/packages/server/src/live-server/live-server-proxy.ts +128 -0
- package/packages/server/src/live-server/live-server-proxy.ts.AGENTS.md +3 -0
- package/packages/server/src/metrics/AGENTS.md +9 -0
- package/packages/server/src/metrics/eventloop-sampler.ts +67 -0
- package/packages/server/src/metrics/eventloop-sampler.ts.AGENTS.md +3 -0
- package/packages/server/src/metrics/eventloop-spike-metrics.ts +53 -0
- package/packages/server/src/metrics/eventloop-spike-metrics.ts.AGENTS.md +3 -0
- package/packages/server/src/metrics/hydration-metrics.ts +45 -0
- package/packages/server/src/metrics/hydration-metrics.ts.AGENTS.md +3 -0
- package/packages/server/src/model-proxy/AGENTS.md +18 -0
- package/packages/server/src/model-proxy/__tests__/auth-json-contention.test.ts +1 -1
- package/packages/server/src/model-proxy/__tests__/internal-registry.test.ts +167 -0
- package/packages/server/src/model-proxy/__tests__/oauth-compat.test.ts +31 -0
- package/packages/server/src/model-proxy/convert/AGENTS.md +13 -0
- package/packages/server/src/model-proxy/custom-provider-discovery.ts +78 -0
- package/packages/server/src/model-proxy/internal-auth-storage.ts +17 -4
- package/packages/server/src/model-proxy/internal-registry.ts +112 -14
- package/packages/server/src/model-proxy/oauth-compat.ts +47 -0
- package/packages/server/src/model-proxy/registry-singleton.ts +31 -3
- package/packages/server/src/openspec/AGENTS.md +14 -0
- package/packages/server/src/openspec/openspec-archive.ts.AGENTS.md +3 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +161 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts.AGENTS.md +3 -0
- package/packages/server/src/{openspec-group-store.ts → openspec/openspec-group-store.ts} +36 -4
- package/packages/server/src/openspec/openspec-group-store.ts.AGENTS.md +3 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +77 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts.AGENTS.md +3 -0
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +311 -0
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts.AGENTS.md +3 -0
- package/packages/server/src/openspec/openspec-poll-worker.ts +188 -0
- package/packages/server/src/openspec/openspec-poll-worker.ts.AGENTS.md +3 -0
- package/packages/server/src/openspec/openspec-tasks.ts.AGENTS.md +3 -0
- package/packages/server/src/openspec/proposal-attach-naming.ts.AGENTS.md +3 -0
- package/packages/server/src/package/AGENTS.md +12 -0
- package/packages/server/src/{installed-package-enricher.ts → package/installed-package-enricher.ts} +129 -2
- package/packages/server/src/package/installed-package-enricher.ts.AGENTS.md +8 -0
- package/packages/server/src/{npm-search-proxy.ts → package/npm-search-proxy.ts} +31 -0
- package/packages/server/src/package/npm-search-proxy.ts.AGENTS.md +8 -0
- package/packages/server/src/{package-manager-wrapper.ts → package/package-manager-wrapper.ts} +133 -8
- package/packages/server/src/package/package-manager-wrapper.ts.AGENTS.md +8 -0
- package/packages/server/src/package/package-source-helpers.ts.AGENTS.md +3 -0
- package/packages/server/src/package/provider-catalogue-cache.ts.AGENTS.md +3 -0
- package/packages/server/src/{provider-probe.ts → package/provider-probe.ts} +35 -0
- package/packages/server/src/package/provider-probe.ts.AGENTS.md +3 -0
- package/packages/server/src/pairing/AGENTS.md +9 -0
- package/packages/server/src/{browser-gateway.ts → pairing/browser-gateway.ts} +311 -39
- package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +3 -0
- package/packages/server/src/pairing/paired-devices.ts +141 -0
- package/packages/server/src/pairing/paired-devices.ts.AGENTS.md +3 -0
- package/packages/server/src/pairing/pairing.ts +274 -0
- package/packages/server/src/pairing/pairing.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/AGENTS.md +16 -0
- package/packages/server/src/{pending-attach-registry.ts → pending/pending-attach-registry.ts} +1 -1
- package/packages/server/src/pending/pending-attach-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-automation-run-registry.ts +116 -0
- package/packages/server/src/pending/pending-automation-run-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-client-correlations.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-fork-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-goal-link-registry.ts +107 -0
- package/packages/server/src/pending/pending-goal-link-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-initial-prompt-registry.ts +105 -0
- package/packages/server/src/pending/pending-initial-prompt-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-load-manager.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-resume-intent-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-resume-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/pending/pending-worktree-base-registry.ts +108 -0
- package/packages/server/src/pending/pending-worktree-base-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/persistence/AGENTS.md +11 -0
- package/packages/server/src/persistence/json-store.ts.AGENTS.md +3 -0
- package/packages/server/src/persistence/memory-event-store.ts +500 -0
- package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +3 -0
- package/packages/server/src/persistence/meta-persistence.ts +140 -0
- package/packages/server/src/persistence/meta-persistence.ts.AGENTS.md +3 -0
- package/packages/server/src/{migrate-persistence.ts → persistence/migrate-persistence.ts} +6 -4
- package/packages/server/src/persistence/migrate-persistence.ts.AGENTS.md +3 -0
- package/packages/server/src/persistence/preferences-store.ts +577 -0
- package/packages/server/src/persistence/preferences-store.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/AGENTS.md +14 -0
- package/packages/server/src/{pi-core-checker.ts → pi/pi-core-checker.ts} +2 -2
- package/packages/server/src/pi/pi-core-checker.ts.AGENTS.md +3 -0
- package/packages/server/src/{pi-core-updater.ts → pi/pi-core-updater.ts} +1 -1
- package/packages/server/src/pi/pi-core-updater.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/pi-dev-version-check.ts.AGENTS.md +3 -0
- package/packages/server/src/{pi-gateway.ts → pi/pi-gateway.ts} +60 -9
- package/packages/server/src/pi/pi-gateway.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/pi-resource-activation.ts +153 -0
- package/packages/server/src/pi/pi-resource-activation.ts.AGENTS.md +3 -0
- package/packages/server/src/{pi-resource-scanner.ts → pi/pi-resource-scanner.ts} +98 -7
- package/packages/server/src/pi/pi-resource-scanner.ts.AGENTS.md +3 -0
- package/packages/server/src/{pi-version-skew.ts → pi/pi-version-skew.ts} +6 -3
- package/packages/server/src/pi/pi-version-skew.ts.AGENTS.md +3 -0
- package/packages/server/src/pi/resource-activation-toggle.ts +221 -0
- package/packages/server/src/pi/resource-activation-toggle.ts.AGENTS.md +3 -0
- package/packages/server/src/plugin-intent-cache.ts.AGENTS.md +3 -0
- package/packages/server/src/ripgrep-detection.ts +28 -0
- package/packages/server/src/routes/AGENTS.md +38 -0
- package/packages/server/src/routes/__tests__/grep-routes.test.ts +84 -0
- package/packages/server/src/routes/canvas-types-routes.ts +73 -0
- package/packages/server/src/routes/doctor-routes.ts +56 -13
- package/packages/server/src/routes/file-routes.ts +978 -27
- package/packages/server/src/routes/git-routes.ts +839 -13
- package/packages/server/src/routes/goal-routes.ts +401 -0
- package/packages/server/src/routes/grep-routes.ts +67 -0
- package/packages/server/src/routes/live-server-routes.ts +52 -0
- package/packages/server/src/routes/model-proxy-diagnostics-routes.ts +30 -0
- package/packages/server/src/routes/model-proxy-routes.ts +88 -33
- package/packages/server/src/routes/models-introspection-routes.ts +78 -0
- package/packages/server/src/routes/openspec-group-routes.ts +32 -3
- package/packages/server/src/routes/openspec-routes.ts +244 -17
- package/packages/server/src/routes/package-routes.ts +72 -7
- package/packages/server/src/routes/pairing-routes.ts +154 -0
- package/packages/server/src/routes/pi-changelog-routes.ts +11 -10
- package/packages/server/src/routes/pi-core-routes.ts +3 -3
- package/packages/server/src/routes/preferences-auto-name-routes.ts +51 -0
- package/packages/server/src/routes/preferences-display-routes.ts +52 -0
- package/packages/server/src/routes/preferences-worktree-init-routes.ts +46 -0
- package/packages/server/src/routes/provider-auth-routes.ts +15 -6
- package/packages/server/src/routes/provider-routes.ts +36 -6
- package/packages/server/src/routes/recommended-routes.ts +47 -5
- package/packages/server/src/routes/resource-activation-routes.ts +132 -0
- package/packages/server/src/routes/route-deps.ts +4 -4
- package/packages/server/src/routes/session-routes.ts +65 -8
- package/packages/server/src/routes/system-routes.ts +260 -84
- package/packages/server/src/routes/tool-routes.ts +7 -2
- package/packages/server/src/rpc-keeper/AGENTS.md +8 -0
- package/packages/server/src/rpc-keeper/__tests__/fixtures/mock-pi.cjs +39 -0
- package/packages/server/src/rpc-keeper/__tests__/keeper-electron-run-as-node.test.ts +67 -0
- package/packages/server/src/rpc-keeper/__tests__/keeper-env.test.ts +47 -0
- package/packages/server/src/rpc-keeper/__tests__/keeper-shutdown-kills-pi.test.ts +134 -0
- package/packages/server/src/rpc-keeper/__tests__/keeper.test.ts +148 -2
- package/packages/server/src/rpc-keeper/dispatch-router.ts +1 -1
- package/packages/server/src/rpc-keeper/keeper-env.cjs +28 -0
- package/packages/server/src/rpc-keeper/keeper-manager.ts +37 -4
- package/packages/server/src/rpc-keeper/keeper.cjs +66 -8
- package/packages/server/src/server.ts +1124 -228
- package/packages/server/src/server.ts.AGENTS.md +3 -0
- package/packages/server/src/session/AGENTS.md +26 -0
- package/packages/server/src/session/__tests__/session-diff-cache.test.ts +62 -0
- package/packages/server/src/session/__tests__/session-diff-eventloop.test.ts +79 -0
- package/packages/server/src/session/active-sessions-in-cwd.ts +80 -0
- package/packages/server/src/session/active-sessions-in-cwd.ts.AGENTS.md +3 -0
- package/packages/server/src/session/event-status-extraction.ts.AGENTS.md +3 -0
- package/packages/server/src/{memory-session-manager.ts → session/memory-session-manager.ts} +28 -1
- package/packages/server/src/session/memory-session-manager.ts.AGENTS.md +3 -0
- package/packages/server/src/{reattach-placement.ts → session/reattach-placement.ts} +1 -1
- package/packages/server/src/session/reattach-placement.ts.AGENTS.md +3 -0
- package/packages/server/src/session/reconcile-session-order.ts +62 -0
- package/packages/server/src/session/reconcile-session-order.ts.AGENTS.md +3 -0
- package/packages/server/src/session/replay-truncate.ts +73 -0
- package/packages/server/src/session/replay-truncate.ts.AGENTS.md +3 -0
- package/packages/server/src/session/resolve-order-key.ts +36 -0
- package/packages/server/src/session/resolve-order-key.ts.AGENTS.md +3 -0
- package/packages/server/src/{session-api.ts → session/session-api.ts} +13 -10
- package/packages/server/src/session/session-api.ts.AGENTS.md +3 -0
- package/packages/server/src/{session-bootstrap.ts → session/session-bootstrap.ts} +24 -10
- package/packages/server/src/session/session-bootstrap.ts.AGENTS.md +3 -0
- package/packages/server/src/session/session-diff-cache.ts +90 -0
- package/packages/server/src/session/session-diff.ts +845 -0
- package/packages/server/src/session/session-diff.ts.AGENTS.md +9 -0
- package/packages/server/src/{session-discovery.ts → session/session-discovery.ts} +3 -2
- package/packages/server/src/session/session-discovery.ts.AGENTS.md +3 -0
- package/packages/server/src/{session-file-reader.ts → session/session-file-reader.ts} +42 -2
- package/packages/server/src/session/session-file-reader.ts.AGENTS.md +3 -0
- package/packages/server/src/session/session-load-worker-pool.ts +307 -0
- package/packages/server/src/session/session-load-worker-pool.ts.AGENTS.md +3 -0
- package/packages/server/src/session/session-load-worker.ts +79 -0
- package/packages/server/src/session/session-load-worker.ts.AGENTS.md +3 -0
- package/packages/server/src/{session-order-manager.ts → session/session-order-manager.ts} +37 -1
- package/packages/server/src/session/session-order-manager.ts.AGENTS.md +3 -0
- package/packages/server/src/{session-scanner.ts → session/session-scanner.ts} +51 -5
- package/packages/server/src/session/session-scanner.ts.AGENTS.md +3 -0
- package/packages/server/src/session/session-stats-reader.ts.AGENTS.md +3 -0
- package/packages/server/src/session/session-to-meta.ts +67 -0
- package/packages/server/src/session/session-to-meta.ts.AGENTS.md +3 -0
- package/packages/server/src/session/viewed-session-tracker.ts.AGENTS.md +3 -0
- package/packages/server/src/spawn-process/AGENTS.md +16 -0
- package/packages/server/src/{headless-pid-registry.ts → spawn-process/headless-pid-registry.ts} +134 -58
- package/packages/server/src/spawn-process/headless-pid-registry.ts.AGENTS.md +3 -0
- package/packages/server/src/{idle-timer.ts → spawn-process/idle-timer.ts} +2 -2
- package/packages/server/src/spawn-process/idle-timer.ts.AGENTS.md +3 -0
- package/packages/server/src/spawn-process/process-classifier.ts +110 -0
- package/packages/server/src/spawn-process/process-classifier.ts.AGENTS.md +3 -0
- package/packages/server/src/{process-manager.ts → spawn-process/process-manager.ts} +105 -222
- package/packages/server/src/spawn-process/process-manager.ts.AGENTS.md +3 -0
- package/packages/server/src/{restart-helper.ts → spawn-process/restart-helper.ts} +36 -6
- package/packages/server/src/spawn-process/restart-helper.ts.AGENTS.md +3 -0
- package/packages/server/src/spawn-process/server-pid.ts.AGENTS.md +3 -0
- package/packages/server/src/{spawn-preflight.ts → spawn-process/spawn-preflight.ts} +7 -1
- package/packages/server/src/spawn-process/spawn-preflight.ts.AGENTS.md +3 -0
- package/packages/server/src/{spawn-register-watchdog.ts → spawn-process/spawn-register-watchdog.ts} +5 -4
- package/packages/server/src/spawn-process/spawned-turn-log.ts +103 -0
- package/packages/server/src/spawn-process/spawned-turn-log.ts.AGENTS.md +3 -0
- package/packages/server/src/system-open-capability.ts +87 -0
- package/packages/server/src/terminal/AGENTS.md +8 -0
- package/packages/server/src/terminal/terminal-gateway.ts.AGENTS.md +3 -0
- package/packages/server/src/{terminal-manager.ts → terminal/terminal-manager.ts} +24 -5
- package/packages/server/src/terminal/terminal-manager.ts.AGENTS.md +3 -0
- package/packages/server/src/test-support/AGENTS.md +7 -0
- package/packages/server/src/test-support/test-server.ts +2 -2
- package/packages/server/src/tunnel/AGENTS.md +12 -0
- package/packages/server/src/tunnel/tunnel-block-events.ts +83 -0
- package/packages/server/src/tunnel/tunnel-block-events.ts.AGENTS.md +3 -0
- package/packages/server/src/tunnel/tunnel-core.ts +291 -0
- package/packages/server/src/tunnel/tunnel-core.ts.AGENTS.md +3 -0
- package/packages/server/src/tunnel/tunnel-endpoints.ts +76 -0
- package/packages/server/src/tunnel/tunnel-endpoints.ts.AGENTS.md +3 -0
- package/packages/server/src/tunnel/tunnel-enroll.ts +151 -0
- package/packages/server/src/tunnel/tunnel-enroll.ts.AGENTS.md +3 -0
- package/packages/server/src/tunnel/tunnel-watchdog.ts.AGENTS.md +3 -0
- package/packages/server/src/tunnel/tunnel.ts +89 -0
- package/packages/server/src/tunnel/tunnel.ts.AGENTS.md +3 -0
- package/packages/server/src/tunnel-providers/AGENTS.md +13 -0
- package/packages/server/src/tunnel-providers/ngrok.ts +131 -0
- package/packages/server/src/tunnel-providers/tailscale.ts +236 -0
- package/packages/server/src/tunnel-providers/zerotier.ts +139 -0
- package/packages/server/src/tunnel-providers/zrok.ts +245 -0
- package/packages/server/tsconfig.json +0 -3
- package/packages/shared/AGENTS.md +7 -0
- package/packages/shared/package.json +1 -1
- package/packages/shared/src/AGENTS.md +50 -0
- package/packages/shared/src/__tests__/binary-lookup.test.ts +12 -1
- package/packages/shared/src/__tests__/browser-protocol-types.test.ts +65 -0
- package/packages/shared/src/__tests__/bundled-node-meets-pi-floor.test.ts +109 -0
- package/packages/shared/src/__tests__/bundled-plugins-complete.test.ts +90 -0
- package/packages/shared/src/__tests__/bundled-server-materialization.test.ts +93 -0
- package/packages/shared/src/__tests__/canvas-declare.test.ts +103 -0
- package/packages/shared/src/__tests__/canvas-detect.test.ts +83 -0
- package/packages/shared/src/__tests__/canvas-types.test.ts +46 -0
- package/packages/shared/src/__tests__/config-keeper-log.test.ts +77 -0
- package/packages/shared/src/__tests__/config-openspec.test.ts +3 -3
- package/packages/shared/src/__tests__/config.test.ts +127 -0
- package/packages/shared/src/__tests__/credential-detect.test.ts +145 -0
- package/packages/shared/src/__tests__/cwd-missing-protocol.test.ts +47 -0
- package/packages/shared/src/__tests__/dashboard-paths.test.ts +64 -0
- package/packages/shared/src/__tests__/display-prefs.test.ts +147 -0
- package/packages/shared/src/__tests__/doctor-core-legacy-advisory.test.ts +88 -0
- package/packages/shared/src/__tests__/doctor-core.test.ts +104 -4
- package/packages/shared/src/__tests__/doctor-format.test.ts +5 -2
- package/packages/shared/src/__tests__/doctor-tunnel-checks.test.ts +422 -0
- package/packages/shared/src/__tests__/ensure-bundled-git.test.ts +111 -0
- package/packages/shared/src/__tests__/file-kind.test.ts +199 -0
- package/packages/shared/src/__tests__/intent-types.test.ts +1 -1
- package/packages/shared/src/__tests__/live-server.test.ts +75 -0
- package/packages/shared/src/__tests__/model-id.test.ts +31 -0
- package/packages/shared/src/__tests__/model-proxy-config.test.ts +37 -0
- package/packages/shared/src/__tests__/no-bash-on-windows.test.ts +4 -0
- package/packages/shared/src/__tests__/no-direct-child-process.test.ts +1 -1
- package/packages/shared/src/__tests__/no-direct-platform-branch.test.ts +16 -8
- package/packages/shared/src/__tests__/no-hardcoded-bundled-git-paths.test.ts +95 -0
- package/packages/shared/src/__tests__/no-managed-dir-reference.test.ts +6 -3
- package/packages/shared/src/__tests__/no-primitive-direct-import.test.ts +2 -1
- package/packages/shared/src/__tests__/no-remote-debugging-address.test.ts +72 -0
- package/packages/shared/src/__tests__/node-version.test.ts +59 -0
- package/packages/shared/src/__tests__/openspec-poller-derive.test.ts +115 -0
- package/packages/shared/src/__tests__/openspec-poller-parity.test.ts +77 -0
- package/packages/shared/src/__tests__/pi-version-update-protocol.test.ts +30 -0
- package/packages/shared/src/__tests__/platform-commands.test.ts +44 -16
- package/packages/shared/src/__tests__/platform-git.test.ts +117 -11
- package/packages/shared/src/__tests__/platform-openspec.test.ts +3 -0
- package/packages/shared/src/__tests__/plugin-activation-contracts.test.ts +16 -12
- package/packages/shared/src/__tests__/protocol.test.ts +22 -0
- package/packages/shared/src/__tests__/publish-allowlist-complete.test.ts +146 -0
- package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +181 -34
- package/packages/shared/src/__tests__/recommended-extensions.test.ts +79 -40
- package/packages/shared/src/__tests__/recovery-candidate.test.ts +51 -0
- package/packages/shared/src/__tests__/resolver-parity-with-scanner.test.ts +1 -0
- package/packages/shared/src/__tests__/role-name-validation.test.ts +46 -0
- package/packages/shared/src/__tests__/select-git-source.test.ts +65 -0
- package/packages/shared/src/__tests__/server-launcher.test.ts +67 -0
- package/packages/shared/src/__tests__/session-meta-worktree.test.ts +61 -0
- package/packages/shared/src/__tests__/session-meta.test.ts +15 -0
- package/packages/shared/src/__tests__/source-matching.test.ts +55 -0
- package/packages/shared/src/__tests__/state-replay-flow-events.test.ts +100 -0
- package/packages/shared/src/__tests__/tags.test.ts +65 -0
- package/packages/shared/src/__tests__/tool-registry-definitions.test.ts +166 -16
- package/packages/shared/src/__tests__/tunnel-config-migration.test.ts +111 -0
- package/packages/shared/src/__tests__/tunnel-provider.test.ts +54 -0
- package/packages/shared/src/browser-protocol.ts +598 -82
- package/packages/shared/src/canvas-declare.ts +132 -0
- package/packages/shared/src/canvas-detect.ts +74 -0
- package/packages/shared/src/canvas-types.ts +42 -0
- package/packages/shared/src/config.ts +346 -56
- package/packages/shared/src/credential-detect.ts +96 -0
- package/packages/shared/src/dashboard-paths.ts +54 -3
- package/packages/shared/src/dashboard-plugin/AGENTS.md +14 -0
- package/packages/shared/src/dashboard-plugin/intent-types.ts +18 -0
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +37 -1
- package/packages/shared/src/dashboard-plugin/route-descriptor.ts +103 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +43 -0
- package/packages/shared/src/dashboard-plugin/slot-types.ts +44 -12
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +63 -0
- package/packages/shared/src/diff-types.ts +74 -9
- package/packages/shared/src/display-prefs.ts +205 -0
- package/packages/shared/src/doctor-core.ts +707 -50
- package/packages/shared/src/file-kind.ts +330 -0
- package/packages/shared/src/git-worktree-helpers.ts +113 -0
- package/packages/shared/src/index.ts +10 -0
- package/packages/shared/src/live-server.ts +86 -0
- package/packages/shared/src/model-id.ts +15 -0
- package/packages/shared/src/node-version.ts +84 -0
- package/packages/shared/src/openspec-poller.ts +45 -0
- package/packages/shared/src/platform/AGENTS.md +28 -0
- package/packages/shared/src/platform/__tests__/openspec-profile-config.test.ts +109 -0
- package/packages/shared/src/platform/__tests__/openspec-runner-stripped-path.integration.test.ts +127 -0
- package/packages/shared/src/platform/__tests__/runner-spawn-env.test.ts +59 -0
- package/packages/shared/src/platform/__tests__/spawn-mechanism.test.ts +57 -0
- package/packages/shared/src/platform/binary-lookup.ts +33 -8
- package/packages/shared/src/platform/commands.ts +53 -15
- package/packages/shared/src/platform/ensure-bundled-git.ts +181 -0
- package/packages/shared/src/platform/ensure-windows-path.ts +2 -2
- package/packages/shared/src/platform/git-source.ts +145 -0
- package/packages/shared/src/platform/git.ts +188 -1
- package/packages/shared/src/platform/git.ts.AGENTS.md +19 -0
- package/packages/shared/src/platform/openspec.ts +160 -1
- package/packages/shared/src/platform/runner.ts +64 -4
- package/packages/shared/src/platform/select-git-source.ts +70 -0
- package/packages/shared/src/platform/spawn-mechanism.ts +31 -3
- package/packages/shared/src/protocol.ts +370 -68
- package/packages/shared/src/recommended-extensions.ts +287 -24
- package/packages/shared/src/renderer-by-ext.ts +94 -0
- package/packages/shared/src/rest-api.ts +201 -3
- package/packages/shared/src/role-name-validation.ts +39 -0
- package/packages/shared/src/session-group-path.ts +68 -0
- package/packages/shared/src/session-meta.ts +142 -0
- package/packages/shared/src/source-matching.ts +20 -0
- package/packages/shared/src/state-replay.ts +28 -0
- package/packages/shared/src/tags.ts +90 -0
- package/packages/shared/src/terminal-types.ts +7 -0
- package/packages/shared/src/test-support/AGENTS.md +8 -0
- package/packages/shared/src/test-support/setup-home-perfile.ts +43 -0
- package/packages/shared/src/tool-registry/AGENTS.md +12 -0
- package/packages/shared/src/tool-registry/__tests__/bare-import-exports-map.test.ts +77 -0
- package/packages/shared/src/tool-registry/__tests__/bundled-git-bash-strategy.test.ts +74 -0
- package/packages/shared/src/tool-registry/__tests__/bundled-node-strategy.test.ts +125 -0
- package/packages/shared/src/tool-registry/__tests__/install-hints.test.ts +126 -0
- package/packages/shared/src/tool-registry/__tests__/node-electron-resolution.test.ts +242 -0
- package/packages/shared/src/tool-registry/__tests__/node-script-argv-matrix.test.ts +157 -0
- package/packages/shared/src/tool-registry/__tests__/openspec-unix-node-wrap.test.ts +62 -0
- package/packages/shared/src/tool-registry/__tests__/pi-ai-registration.test.ts +6 -0
- package/packages/shared/src/tool-registry/definitions.ts +333 -44
- package/packages/shared/src/tool-registry/registry.ts +36 -4
- package/packages/shared/src/tool-registry/strategies.ts +227 -1
- package/packages/shared/src/tool-registry/types.ts +52 -1
- package/packages/shared/src/tunnel-provider.ts +133 -0
- package/packages/shared/src/types.ts +548 -39
- package/packages/shared/src/zrok-env.ts +125 -0
- package/scripts/AGENTS.md +38 -0
- package/scripts/fix-pty-permissions.cjs +67 -0
- package/packages/extension/src/__tests__/bridge-retry-ordering.test.ts +0 -148
- package/packages/extension/src/__tests__/bridge-shadow-queue-drain.test.ts +0 -221
- package/packages/extension/src/__tests__/fixtures/usage-limit-error-strings.ts +0 -127
- package/packages/extension/src/__tests__/usage-limit-orderer.test.ts +0 -117
- package/packages/extension/src/__tests__/vcs-info-jj.test.ts +0 -145
- package/packages/extension/src/usage-limit-orderer.ts +0 -93
- package/packages/server/src/__tests__/editor-detection.test.ts +0 -60
- package/packages/server/src/__tests__/editor-endpoints.test.ts +0 -26
- package/packages/server/src/__tests__/editor-manager-pid-registry.test.ts +0 -168
- package/packages/server/src/__tests__/editor-manager.test.ts +0 -106
- package/packages/server/src/__tests__/editor-pid-registry.test.ts +0 -191
- package/packages/server/src/__tests__/editor-registry.test.ts +0 -165
- package/packages/server/src/__tests__/jj-routes.test.ts +0 -93
- package/packages/server/src/__tests__/session-action-handler-clear-queue.test.ts +0 -153
- package/packages/server/src/__tests__/session-diff-vcs.test.ts +0 -61
- package/packages/server/src/editor-detection.ts +0 -63
- package/packages/server/src/editor-manager.ts +0 -386
- package/packages/server/src/editor-pid-registry.ts +0 -199
- package/packages/server/src/editor-proxy.ts +0 -134
- package/packages/server/src/editor-registry.ts +0 -105
- package/packages/server/src/git-operations.ts +0 -200
- package/packages/server/src/memory-event-store.ts +0 -193
- package/packages/server/src/meta-persistence.ts +0 -64
- package/packages/server/src/node-guard.ts +0 -52
- package/packages/server/src/preferences-store.ts +0 -316
- package/packages/server/src/routes/editor-routes.ts +0 -86
- package/packages/server/src/routes/jj-routes.ts +0 -389
- package/packages/server/src/session-diff.ts +0 -295
- package/packages/server/src/tunnel.ts +0 -471
- package/packages/shared/src/__tests__/platform-jj.test.ts +0 -339
- package/packages/shared/src/editor-types.ts +0 -18
- package/packages/shared/src/platform/jj.ts +0 -405
- /package/packages/server/src/{oauth-callback-server.ts → auth/oauth-callback-server.ts} +0 -0
- /package/packages/server/src/{spawn-token.ts → auth/spawn-token.ts} +0 -0
- /package/packages/server/src/{test-env-guard.ts → auth/test-env-guard.ts} +0 -0
- /package/packages/server/src/{changelog-parser.ts → changelog/changelog-parser.ts} +0 -0
- /package/packages/server/src/{changelog-remote.ts → changelog/changelog-remote.ts} +0 -0
- /package/packages/server/src/{home-lock-release.ts → lifecycle/home-lock-release.ts} +0 -0
- /package/packages/server/src/{home-lock.ts → lifecycle/home-lock.ts} +0 -0
- /package/packages/server/src/{openspec-archive.ts → openspec/openspec-archive.ts} +0 -0
- /package/packages/server/src/{openspec-tasks.ts → openspec/openspec-tasks.ts} +0 -0
- /package/packages/server/src/{proposal-attach-naming.ts → openspec/proposal-attach-naming.ts} +0 -0
- /package/packages/server/src/{package-source-helpers.ts → package/package-source-helpers.ts} +0 -0
- /package/packages/server/src/{provider-catalogue-cache.ts → package/provider-catalogue-cache.ts} +0 -0
- /package/packages/server/src/{pending-client-correlations.ts → pending/pending-client-correlations.ts} +0 -0
- /package/packages/server/src/{pending-fork-registry.ts → pending/pending-fork-registry.ts} +0 -0
- /package/packages/server/src/{pending-load-manager.ts → pending/pending-load-manager.ts} +0 -0
- /package/packages/server/src/{pending-resume-intent-registry.ts → pending/pending-resume-intent-registry.ts} +0 -0
- /package/packages/server/src/{pending-resume-registry.ts → pending/pending-resume-registry.ts} +0 -0
- /package/packages/server/src/{json-store.ts → persistence/json-store.ts} +0 -0
- /package/packages/server/src/{pi-dev-version-check.ts → pi/pi-dev-version-check.ts} +0 -0
- /package/packages/server/src/{event-status-extraction.ts → session/event-status-extraction.ts} +0 -0
- /package/packages/server/src/{session-stats-reader.ts → session/session-stats-reader.ts} +0 -0
- /package/packages/server/src/{viewed-session-tracker.ts → session/viewed-session-tracker.ts} +0 -0
- /package/packages/server/src/{server-pid.ts → spawn-process/server-pid.ts} +0 -0
- /package/packages/server/src/{spawn-failure-log.ts → spawn-process/spawn-failure-log.ts} +0 -0
- /package/packages/server/src/{terminal-gateway.ts → terminal/terminal-gateway.ts} +0 -0
- /package/packages/server/src/{tunnel-watchdog.ts → tunnel/tunnel-watchdog.ts} +0 -0
|
@@ -0,0 +1,1687 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side git operations — branch listing, checkout, init, stash,
|
|
3
|
+
* worktree (head probe, list, create).
|
|
4
|
+
*/
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { type ChildProcess, execFileAsync, execSync, spawn } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
8
|
+
import { gitStatusV2 } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
|
|
9
|
+
import type { GitChangedFile, GitCommitResult } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
|
|
10
|
+
import type { GitStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
11
|
+
// Self-namespace import so `resolveConfigRoot` calls `isGitRepo`/`resolveMainPath`
|
|
12
|
+
// through the module's live exports — lets tests stub them (internal lexical
|
|
13
|
+
// references are otherwise un-spyable). See change: support-non-git-init-hook.
|
|
14
|
+
import * as self from "./git-operations.js";
|
|
15
|
+
import {
|
|
16
|
+
ensureWorktreeExcludeLine,
|
|
17
|
+
isOrphanWorktreePath,
|
|
18
|
+
parsePorcelainWorktrees,
|
|
19
|
+
resolveCheckoutLocalName,
|
|
20
|
+
slugifyBranch,
|
|
21
|
+
type WorktreeEntry,
|
|
22
|
+
} from "./git-worktree.js";
|
|
23
|
+
|
|
24
|
+
const GIT_TIMEOUT = 15_000;
|
|
25
|
+
|
|
26
|
+
/** Run a git command, return trimmed stdout. Throws on failure. */
|
|
27
|
+
function run(command: string, cwd: string): string {
|
|
28
|
+
return execSync(command, {
|
|
29
|
+
cwd,
|
|
30
|
+
encoding: "utf-8",
|
|
31
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
32
|
+
timeout: GIT_TIMEOUT,
|
|
33
|
+
}).trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Run a git command, return trimmed stdout or undefined on failure. */
|
|
37
|
+
function tryRun(command: string, cwd: string): string | undefined {
|
|
38
|
+
try {
|
|
39
|
+
return run(command, cwd);
|
|
40
|
+
} catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Check if cwd is inside a git work tree. */
|
|
46
|
+
export function isGitRepo(cwd: string): boolean {
|
|
47
|
+
return tryRun("git rev-parse --is-inside-work-tree", cwd) === "true";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Get list of dirty files from git status --porcelain. */
|
|
51
|
+
export function getDirtyFiles(cwd: string): string[] {
|
|
52
|
+
let output: string;
|
|
53
|
+
try {
|
|
54
|
+
output = execSync("git status --porcelain", {
|
|
55
|
+
cwd,
|
|
56
|
+
encoding: "utf-8",
|
|
57
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
58
|
+
timeout: GIT_TIMEOUT,
|
|
59
|
+
});
|
|
60
|
+
} catch {
|
|
61
|
+
return [];
|
|
62
|
+
}
|
|
63
|
+
return output
|
|
64
|
+
.split("\n")
|
|
65
|
+
.filter((line) => line.length > 0)
|
|
66
|
+
.map((line) => line.slice(3)); // strip 2 status chars + space
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Fresh working-tree dirtiness + upstream drift for `cwd`. Reuses the shared
|
|
71
|
+
* porcelain-v2 parser so the on-demand server read matches the bridge
|
|
72
|
+
* broadcast byte-for-byte. Returns `undefined` on an inconclusive probe
|
|
73
|
+
* (git missing, not a repo, timeout). See change:
|
|
74
|
+
* add-session-uncommitted-indicator-and-commit.
|
|
75
|
+
*/
|
|
76
|
+
export function getGitStatus(cwd: string): GitStatus | undefined {
|
|
77
|
+
const res = gitStatusV2({ cwd });
|
|
78
|
+
return res.ok ? res.value : undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Error thrown by `commitFiles` carrying a stable machine-readable `code`
|
|
83
|
+
* so the route can surface it to the dialog without string-matching stderr.
|
|
84
|
+
*/
|
|
85
|
+
export class GitCommitError extends Error {
|
|
86
|
+
constructor(
|
|
87
|
+
public code:
|
|
88
|
+
| "not-a-repo"
|
|
89
|
+
| "path-escape"
|
|
90
|
+
| "no-files"
|
|
91
|
+
| "empty-message"
|
|
92
|
+
| "stage-failed"
|
|
93
|
+
| "commit-failed",
|
|
94
|
+
message: string,
|
|
95
|
+
) {
|
|
96
|
+
super(message);
|
|
97
|
+
this.name = "GitCommitError";
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Resolve each repo-relative `file` against `cwd` and confirm it stays inside
|
|
103
|
+
* `cwd`. Rejects absolute paths and `..` traversal that would escape the
|
|
104
|
+
* working tree, AND root-equivalent inputs (`""`, `"."`, cwd itself) that would
|
|
105
|
+
* resolve to `git add -- .` and stage the WHOLE tree instead of a chosen file.
|
|
106
|
+
* Returns the sanitized repo-relative paths (normalized) for use in the
|
|
107
|
+
* `git add -- <paths>` argv. Throws `GitCommitError` (`path-escape`) on the
|
|
108
|
+
* first offender. See change:
|
|
109
|
+
* add-session-uncommitted-indicator-and-commit (security-hardening).
|
|
110
|
+
*/
|
|
111
|
+
export function assertPathsInside(cwd: string, files: string[]): string[] {
|
|
112
|
+
const root = path.resolve(cwd);
|
|
113
|
+
const rootWithSep = root.endsWith(path.sep) ? root : root + path.sep;
|
|
114
|
+
return files.map((f) => {
|
|
115
|
+
const abs = path.resolve(root, f);
|
|
116
|
+
// Root-equivalent (empty / "." / cwd itself) would stage everything — the
|
|
117
|
+
// picker always supplies concrete file paths, so reject it explicitly.
|
|
118
|
+
if (abs === root) {
|
|
119
|
+
throw new GitCommitError("path-escape", `path resolves to the repo root, not a file: ${JSON.stringify(f)}`);
|
|
120
|
+
}
|
|
121
|
+
if (!abs.startsWith(rootWithSep)) {
|
|
122
|
+
throw new GitCommitError("path-escape", `path escapes cwd: ${f}`);
|
|
123
|
+
}
|
|
124
|
+
// Return the path relative to cwd so the argv is stable regardless of
|
|
125
|
+
// how the client expressed it. `--` in the git argv still guards against
|
|
126
|
+
// a leading-dash path being read as a flag.
|
|
127
|
+
return path.relative(root, abs);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Spawn git with an argv (no shell) and optional stdin. Never interpolates. */
|
|
132
|
+
function runGitCapture(
|
|
133
|
+
args: string[],
|
|
134
|
+
cwd: string,
|
|
135
|
+
stdin?: string,
|
|
136
|
+
): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
let stdout = "";
|
|
139
|
+
let stderr = "";
|
|
140
|
+
let child: ChildProcess;
|
|
141
|
+
try {
|
|
142
|
+
child = spawn("git", args, {
|
|
143
|
+
cwd,
|
|
144
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
145
|
+
});
|
|
146
|
+
} catch (err) {
|
|
147
|
+
reject(err);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
let settled = false;
|
|
151
|
+
const done = (fn: () => void) => { if (settled) return; settled = true; clearTimeout(timer); fn(); };
|
|
152
|
+
// Timeout: SIGTERM, then SIGKILL escalation, then reject so a wedged git
|
|
153
|
+
// never leaves the promise pending forever.
|
|
154
|
+
const timer = setTimeout(() => {
|
|
155
|
+
try { child.kill("SIGTERM"); } catch { /* ignore */ }
|
|
156
|
+
setTimeout(() => { try { child.kill("SIGKILL"); } catch { /* ignore */ } }, 2_000);
|
|
157
|
+
done(() => reject(new Error(`git timed out after ${GIT_TIMEOUT}ms: git ${args[0]}`)));
|
|
158
|
+
}, GIT_TIMEOUT);
|
|
159
|
+
child.stdout?.on("data", (c: Buffer) => { stdout += c.toString("utf-8"); });
|
|
160
|
+
child.stderr?.on("data", (c: Buffer) => { stderr += c.toString("utf-8"); });
|
|
161
|
+
child.on("error", (err) => { done(() => reject(err)); });
|
|
162
|
+
child.on("close", (code) => {
|
|
163
|
+
done(() => resolve({ code: code ?? -1, stdout, stderr }));
|
|
164
|
+
});
|
|
165
|
+
if (stdin !== undefined) {
|
|
166
|
+
child.stdin?.end(stdin);
|
|
167
|
+
} else {
|
|
168
|
+
child.stdin?.end();
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Stage the selected `files` and commit them with `message`.
|
|
175
|
+
*
|
|
176
|
+
* Security invariants (security-hardening):
|
|
177
|
+
* - argv arrays only — NO shell, so metacharacters in paths cannot execute.
|
|
178
|
+
* - message via `git commit -F -` stdin — never interpolated into a command
|
|
179
|
+
* string; multi-line bodies and `$()`/backticks are committed verbatim.
|
|
180
|
+
* - every path is `assertPathsInside(cwd)`-guarded before staging.
|
|
181
|
+
*
|
|
182
|
+
* Stages ONLY the selected paths (`git add -- <files>`), then commits the
|
|
183
|
+
* index. Because staging is scoped to the chosen files, unselected changes
|
|
184
|
+
* stay in the working tree. Returns `{ commitHash, subject }`.
|
|
185
|
+
*
|
|
186
|
+
* See change: add-session-uncommitted-indicator-and-commit.
|
|
187
|
+
*/
|
|
188
|
+
export async function commitFiles(opts: {
|
|
189
|
+
cwd: string;
|
|
190
|
+
message: string;
|
|
191
|
+
files: string[];
|
|
192
|
+
}): Promise<GitCommitResult> {
|
|
193
|
+
const { cwd, message, files } = opts;
|
|
194
|
+
if (!self.isGitRepo(cwd)) throw new GitCommitError("not-a-repo", "cwd is not a git repository");
|
|
195
|
+
if (files.length === 0) throw new GitCommitError("no-files", "no files selected");
|
|
196
|
+
if (message.trim().length === 0) throw new GitCommitError("empty-message", "commit message is empty");
|
|
197
|
+
|
|
198
|
+
const safePaths = assertPathsInside(cwd, files);
|
|
199
|
+
|
|
200
|
+
const staged = await runGitCapture(["add", "--", ...safePaths], cwd);
|
|
201
|
+
if (staged.code !== 0) {
|
|
202
|
+
throw new GitCommitError("stage-failed", staged.stderr.trim() || "git add failed");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const committed = await runGitCapture(["commit", "-F", "-", "--", ...safePaths], cwd, message);
|
|
206
|
+
if (committed.code !== 0) {
|
|
207
|
+
throw new GitCommitError("commit-failed", committed.stderr.trim() || "git commit failed");
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const head = await runGitCapture(["rev-parse", "HEAD"], cwd);
|
|
211
|
+
const subjectRes = await runGitCapture(["log", "-1", "--pretty=%s"], cwd);
|
|
212
|
+
return {
|
|
213
|
+
commitHash: head.stdout.trim(),
|
|
214
|
+
subject: subjectRes.stdout.trim(),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* List changed files (staged, unstaged, untracked) with per-file line
|
|
220
|
+
* additions/deletions for the commit dialog picker. Parses
|
|
221
|
+
* `git status --porcelain=v2 --branch` for the file set + state, and
|
|
222
|
+
* `git diff --numstat` (HEAD, then untracked via /dev/null) for counts.
|
|
223
|
+
* Untracked files report their full line count as additions.
|
|
224
|
+
* See change: add-session-uncommitted-indicator-and-commit.
|
|
225
|
+
*/
|
|
226
|
+
export async function getChangedFiles(cwd: string): Promise<GitChangedFile[]> {
|
|
227
|
+
const statusRes = await runGitCapture(["status", "--porcelain=v2", "--branch"], cwd);
|
|
228
|
+
// Propagate a real git failure instead of masking it as "no changes". A
|
|
229
|
+
// clean tree still exits 0 with empty stdout → `[]` below.
|
|
230
|
+
if (statusRes.code !== 0) {
|
|
231
|
+
throw new GitCommitError("not-a-repo", statusRes.stderr.trim() || "git status failed");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const files: GitChangedFile[] = [];
|
|
235
|
+
for (const line of statusRes.stdout.split("\n")) {
|
|
236
|
+
if (line.length === 0) continue;
|
|
237
|
+
const kind = line[0];
|
|
238
|
+
if (kind === "?") {
|
|
239
|
+
files.push({ path: line.slice(2), state: "untracked" });
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
if (kind === "1" || kind === "2" || kind === "u") {
|
|
243
|
+
const parts = line.split(" ");
|
|
244
|
+
const xy = parts[1] ?? "..";
|
|
245
|
+
// Fixed field count before the path: 8 for `1`, 9 for `2` (rename
|
|
246
|
+
// score), 10 for `u` (three stage hashes). For renames the path field
|
|
247
|
+
// is `<newPath>\t<origPath>` — take the new path before the tab. Paths
|
|
248
|
+
// may contain spaces, so rejoin the remaining tokens.
|
|
249
|
+
const skip = kind === "1" ? 8 : kind === "2" ? 9 : 10;
|
|
250
|
+
const p = parts.slice(skip).join(" ").split("\t")[0];
|
|
251
|
+
const staged = xy[0] !== ".";
|
|
252
|
+
files.push({ path: p, state: staged ? "staged" : "unstaged" });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Diffstat counts (best-effort; picker still works without them).
|
|
257
|
+
const numstat = await runGitCapture(["diff", "HEAD", "--numstat"], cwd);
|
|
258
|
+
if (numstat.code === 0) {
|
|
259
|
+
const counts = new Map<string, { additions: number; deletions: number }>();
|
|
260
|
+
for (const line of numstat.stdout.split("\n")) {
|
|
261
|
+
if (!line) continue;
|
|
262
|
+
const [add, del, ...rest] = line.split("\t");
|
|
263
|
+
const p = rest.join("\t");
|
|
264
|
+
counts.set(p, {
|
|
265
|
+
additions: add === "-" ? 0 : parseInt(add, 10) || 0,
|
|
266
|
+
deletions: del === "-" ? 0 : parseInt(del, 10) || 0,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
for (const f of files) {
|
|
270
|
+
const c = counts.get(f.path);
|
|
271
|
+
if (c) { f.additions = c.additions; f.deletions = c.deletions; }
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return files;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export interface BranchInfo {
|
|
278
|
+
current: string;
|
|
279
|
+
detached: boolean;
|
|
280
|
+
branches: Array<{ name: string; isRemote: boolean; isCurrent: boolean }>;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** List all local and remote branches sorted by most recent commit. */
|
|
284
|
+
export function listBranches(cwd: string): BranchInfo {
|
|
285
|
+
// Detect current branch / detached HEAD
|
|
286
|
+
const headRef = tryRun("git rev-parse --abbrev-ref HEAD", cwd);
|
|
287
|
+
|
|
288
|
+
// Empty repo (no commits yet)
|
|
289
|
+
if (!headRef) {
|
|
290
|
+
// Try to read the default branch name from HEAD
|
|
291
|
+
const symbolic = tryRun("git symbolic-ref --short HEAD", cwd);
|
|
292
|
+
return {
|
|
293
|
+
current: symbolic ?? "main",
|
|
294
|
+
detached: false,
|
|
295
|
+
branches: [],
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
const detached = headRef === "HEAD";
|
|
299
|
+
const current = detached
|
|
300
|
+
? run("git rev-parse --short HEAD", cwd)
|
|
301
|
+
: headRef;
|
|
302
|
+
|
|
303
|
+
// List all branches with committer date sorting
|
|
304
|
+
const format = "%(refname:short)%(HEAD)";
|
|
305
|
+
const rawLocal = tryRun(
|
|
306
|
+
`git branch --sort=-committerdate --format="${format}"`,
|
|
307
|
+
cwd
|
|
308
|
+
) ?? "";
|
|
309
|
+
const rawRemote = tryRun(
|
|
310
|
+
`git branch -r --sort=-committerdate --format="${format}"`,
|
|
311
|
+
cwd
|
|
312
|
+
) ?? "";
|
|
313
|
+
|
|
314
|
+
const localBranches: BranchInfo["branches"] = [];
|
|
315
|
+
for (const line of rawLocal.split("\n").filter(Boolean)) {
|
|
316
|
+
const isCurrent = line.includes("*");
|
|
317
|
+
const name = line.replace("*", "").trim();
|
|
318
|
+
if (!name) continue;
|
|
319
|
+
localBranches.push({ name, isRemote: false, isCurrent });
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Collect local branch names for dedup
|
|
323
|
+
const localNames = new Set(localBranches.map((b) => b.name));
|
|
324
|
+
|
|
325
|
+
const remoteBranches: BranchInfo["branches"] = [];
|
|
326
|
+
for (const line of rawRemote.split("\n").filter(Boolean)) {
|
|
327
|
+
const name = line.replace("*", "").trim();
|
|
328
|
+
// Skip HEAD pointers like "origin/HEAD"
|
|
329
|
+
if (name.endsWith("/HEAD")) continue;
|
|
330
|
+
// Skip remote branches that have a local counterpart
|
|
331
|
+
const localName = name.replace(/^[^/]+\//, ""); // "origin/foo" → "foo"
|
|
332
|
+
if (localNames.has(localName)) continue;
|
|
333
|
+
remoteBranches.push({ name, isRemote: true, isCurrent: false });
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
current,
|
|
338
|
+
detached,
|
|
339
|
+
branches: [...localBranches, ...remoteBranches],
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export interface CheckoutResult {
|
|
344
|
+
success: true;
|
|
345
|
+
stashed?: boolean;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export interface CheckoutDirty {
|
|
349
|
+
success: false;
|
|
350
|
+
dirty: true;
|
|
351
|
+
files: string[];
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Checkout a branch. Returns dirty info if working tree is dirty and stash=false. */
|
|
355
|
+
export function checkoutBranch(
|
|
356
|
+
cwd: string,
|
|
357
|
+
branch: string,
|
|
358
|
+
stash: boolean
|
|
359
|
+
): CheckoutResult | CheckoutDirty {
|
|
360
|
+
// Already on this branch?
|
|
361
|
+
const headRef = tryRun("git rev-parse --abbrev-ref HEAD", cwd);
|
|
362
|
+
if (headRef === branch) return { success: true };
|
|
363
|
+
|
|
364
|
+
const dirtyFiles = getDirtyFiles(cwd);
|
|
365
|
+
|
|
366
|
+
if (dirtyFiles.length > 0 && !stash) {
|
|
367
|
+
return { success: false, dirty: true, files: dirtyFiles };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
let stashed = false;
|
|
371
|
+
if (dirtyFiles.length > 0 && stash) {
|
|
372
|
+
run("git stash push -u -m \"pi-dashboard-auto-stash\"", cwd);
|
|
373
|
+
stashed = true;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Check if this is a remote branch that needs a local tracking branch
|
|
377
|
+
const isRemote = branch.includes("/");
|
|
378
|
+
if (isRemote) {
|
|
379
|
+
const localName = branch.replace(/^[^/]+\//, "");
|
|
380
|
+
// Check if local branch exists
|
|
381
|
+
const localExists = tryRun(`git rev-parse --verify refs/heads/${localName}`, cwd);
|
|
382
|
+
if (!localExists) {
|
|
383
|
+
run(`git checkout -b ${localName} ${branch}`, cwd);
|
|
384
|
+
return { success: true, stashed };
|
|
385
|
+
}
|
|
386
|
+
// Local branch exists, just checkout
|
|
387
|
+
run(`git checkout ${localName}`, cwd);
|
|
388
|
+
return { success: true, stashed };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
run(`git checkout ${branch}`, cwd);
|
|
392
|
+
return { success: true, stashed };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Initialize a git repository. Throws if already a git repo. */
|
|
396
|
+
export function gitInit(cwd: string): void {
|
|
397
|
+
if (isGitRepo(cwd)) {
|
|
398
|
+
throw new Error("already a git repository");
|
|
399
|
+
}
|
|
400
|
+
run("git init", cwd);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export interface StashPopResult {
|
|
404
|
+
conflicts: boolean;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// ── Worktree operations ────────────────────────────────────────────────────────────────
|
|
408
|
+
// See change: add-worktree-spawn-dialog.
|
|
409
|
+
|
|
410
|
+
export interface HeadInfo {
|
|
411
|
+
/** Current branch name, or `null` for detached HEAD. */
|
|
412
|
+
branch: string | null;
|
|
413
|
+
detached: boolean;
|
|
414
|
+
/** Short HEAD SHA, or `null` when the repo is empty (no commits yet). */
|
|
415
|
+
sha: string | null;
|
|
416
|
+
/**
|
|
417
|
+
* True iff `.gitmodules` exists at the repo's top level. Used by the
|
|
418
|
+
* worktree dialog to surface a "submodules will not be initialized"
|
|
419
|
+
* footnote. Cheap stat-only probe; never spawns git. Optional on the
|
|
420
|
+
* wire to keep older clients happy.
|
|
421
|
+
*/
|
|
422
|
+
hasSubmodules?: boolean;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Async git runner: trimmed stdout, or `undefined` on any failure. Uses async
|
|
427
|
+
* `execFile` so the git subprocess never blocks the main event loop (unlike the
|
|
428
|
+
* synchronous `run`/`tryRun` above). See change:
|
|
429
|
+
* attribute-openspec-poll-eventloop-stalls.
|
|
430
|
+
*/
|
|
431
|
+
async function tryRunFileAsync(args: string[], cwd: string): Promise<string | undefined> {
|
|
432
|
+
try {
|
|
433
|
+
const { stdout } = await execFileAsync("git", args, {
|
|
434
|
+
cwd,
|
|
435
|
+
encoding: "utf-8",
|
|
436
|
+
timeout: GIT_TIMEOUT,
|
|
437
|
+
});
|
|
438
|
+
return String(stdout).trim();
|
|
439
|
+
} catch {
|
|
440
|
+
return undefined;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Async, non-blocking HEAD read for the folder-head poll. Mirrors `readHead`'s
|
|
446
|
+
* branch/sha derivation (branch name on a branch; detached + short SHA
|
|
447
|
+
* otherwise) but via async `execFile`, so the per-folder git spawns never form
|
|
448
|
+
* one synchronous burst on the poll `setInterval` turn. Intentionally SKIPS the
|
|
449
|
+
* `.gitmodules` submodule probe `readHead` does — the folder-head poll consumes
|
|
450
|
+
* only `deriveDisplayBranch(head)` (branch/sha); the worktree dialog keeps using
|
|
451
|
+
* the sync `readHead` when it needs `hasSubmodules`. See change:
|
|
452
|
+
* attribute-openspec-poll-eventloop-stalls.
|
|
453
|
+
*/
|
|
454
|
+
export async function readHeadDisplayAsync(cwd: string): Promise<HeadInfo> {
|
|
455
|
+
const symbolic = await tryRunFileAsync(["symbolic-ref", "--quiet", "--short", "HEAD"], cwd);
|
|
456
|
+
const sha = (await tryRunFileAsync(["rev-parse", "--short", "HEAD"], cwd)) ?? null;
|
|
457
|
+
if (symbolic) {
|
|
458
|
+
return { branch: symbolic, detached: false, sha };
|
|
459
|
+
}
|
|
460
|
+
return { branch: null, detached: sha !== null, sha };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Read HEAD state of a git repo. */
|
|
464
|
+
export function readHead(cwd: string): HeadInfo {
|
|
465
|
+
// Detect detached HEAD via symbolic-ref --quiet (exits non-zero when detached).
|
|
466
|
+
const symbolic = tryRun("git symbolic-ref --quiet --short HEAD", cwd);
|
|
467
|
+
const sha = tryRun("git rev-parse --short HEAD", cwd) ?? null;
|
|
468
|
+
// `.gitmodules` lives at the worktree's top level (or the main
|
|
469
|
+
// checkout's). Use the worktree's own top level so the probe is correct
|
|
470
|
+
// whether the dialog is opened from a sibling worktree or main.
|
|
471
|
+
const topLevel = tryRun("git rev-parse --show-toplevel", cwd);
|
|
472
|
+
const hasSubmodules = topLevel ? fs.existsSync(path.join(topLevel, ".gitmodules")) : false;
|
|
473
|
+
if (symbolic) {
|
|
474
|
+
return { branch: symbolic, detached: false, sha, hasSubmodules };
|
|
475
|
+
}
|
|
476
|
+
// No symbolic ref → either detached or empty repo.
|
|
477
|
+
return {
|
|
478
|
+
branch: null,
|
|
479
|
+
detached: sha !== null,
|
|
480
|
+
sha,
|
|
481
|
+
hasSubmodules,
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Resolve the directory containing this checkout's git `HEAD` file, worktree-
|
|
487
|
+
* aware. For a main checkout returns `<cwd>/.git`; for a linked worktree
|
|
488
|
+
* (whose `.git` is a file) returns the per-worktree gitdir
|
|
489
|
+
* (`<main>/.git/worktrees/<name>`). Returns `null` when `cwd` is not a git
|
|
490
|
+
* repository. Used by the folder-HEAD watcher to pick the directory to watch.
|
|
491
|
+
* See change: refresh-folder-header-branch.
|
|
492
|
+
*/
|
|
493
|
+
export function resolveGitDir(cwd: string): string | null {
|
|
494
|
+
const out = tryRun("git rev-parse --git-dir", cwd);
|
|
495
|
+
if (!out) return null;
|
|
496
|
+
return path.isAbsolute(out) ? out : path.join(cwd, out);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** List all worktrees of the repository containing `cwd`. */
|
|
500
|
+
export function listWorktrees(cwd: string): WorktreeEntry[] {
|
|
501
|
+
const stdout = run("git worktree list --porcelain", cwd);
|
|
502
|
+
return parsePorcelainWorktrees(stdout);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export type AddWorktreeError =
|
|
506
|
+
| "not_a_repo"
|
|
507
|
+
| "cwd_invalid"
|
|
508
|
+
| "branch_in_use"
|
|
509
|
+
| "branch_exists"
|
|
510
|
+
| "path_exists"
|
|
511
|
+
| "base_not_found"
|
|
512
|
+
| "git_failed";
|
|
513
|
+
|
|
514
|
+
export interface AddWorktreeSuccess {
|
|
515
|
+
ok: true;
|
|
516
|
+
path: string;
|
|
517
|
+
branch: string;
|
|
518
|
+
/** True iff this call appended `.worktrees/` to `.git/info/exclude`. */
|
|
519
|
+
excludeAppended: boolean;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
export interface AddWorktreeFailure {
|
|
523
|
+
ok: false;
|
|
524
|
+
error: AddWorktreeError;
|
|
525
|
+
message: string;
|
|
526
|
+
stderr?: string;
|
|
527
|
+
/**
|
|
528
|
+
* Set on `path_exists` returns. `true` when the target path exists on
|
|
529
|
+
* disk but is NOT a registered worktree (likely orphan from a previous
|
|
530
|
+
* failed attempt); `false` when the path IS a registered worktree.
|
|
531
|
+
* Undefined for non-`path_exists` errors.
|
|
532
|
+
* See change: openspec-worktree-spawn-button.
|
|
533
|
+
*/
|
|
534
|
+
orphanLikely?: boolean;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export interface AddWorktreeOptions {
|
|
538
|
+
/** Cwd inside the parent repo (any worktree's path resolves to the same parent). */
|
|
539
|
+
cwd: string;
|
|
540
|
+
/** Base ref to fork from (local or `origin/<x>`). In checkout mode (no
|
|
541
|
+
* `newBranch`) this is the existing branch ref to check out. */
|
|
542
|
+
base: string;
|
|
543
|
+
/**
|
|
544
|
+
* New branch name to create at the worktree's HEAD (fork mode). When
|
|
545
|
+
* omitted the server runs `git worktree add <path> <base>` (checkout
|
|
546
|
+
* mode) — `base` carries the existing branch ref.
|
|
547
|
+
* See change: worktree-checkout-existing-branch.
|
|
548
|
+
*/
|
|
549
|
+
newBranch?: string;
|
|
550
|
+
/** Optional explicit path; derived from slug when absent. */
|
|
551
|
+
path?: string;
|
|
552
|
+
/** Pass `--force` to `git worktree add` (defaults to false). */
|
|
553
|
+
force?: boolean;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* Create a new worktree. Pure orchestration over `git worktree add` plus
|
|
558
|
+
* the `.git/info/exclude` housekeeping.
|
|
559
|
+
*
|
|
560
|
+
* Returns a discriminated union with stable error codes so the route
|
|
561
|
+
* handler can map straight to HTTP status without re-parsing stderr.
|
|
562
|
+
*/
|
|
563
|
+
export function addWorktree(opts: AddWorktreeOptions): AddWorktreeSuccess | AddWorktreeFailure {
|
|
564
|
+
const { cwd, base, newBranch, force } = opts;
|
|
565
|
+
// Checkout mode = no newBranch. `base` is the existing branch ref to
|
|
566
|
+
// check out. See change: worktree-checkout-existing-branch.
|
|
567
|
+
const checkoutMode = newBranch === undefined;
|
|
568
|
+
if (!isGitRepo(cwd)) {
|
|
569
|
+
return { ok: false, error: "not_a_repo", message: "not a git repository" };
|
|
570
|
+
}
|
|
571
|
+
// Resolve the local branch name + commit-ish for checkout mode.
|
|
572
|
+
// - `base` is a local branch (`refs/heads/<base>` exists) → check it out
|
|
573
|
+
// directly; the branch keeps its full name (e.g. `feat/bar`).
|
|
574
|
+
// - otherwise `base` is a remote-tracking ref (`origin/foo`) → pass the
|
|
575
|
+
// BARE local name (`foo`) so git DWIM-creates a tracking branch.
|
|
576
|
+
// Passing `origin/foo` verbatim would yield a DETACHED HEAD, not a
|
|
577
|
+
// tracking branch, so the bare name is required to get the intended
|
|
578
|
+
// checkout. See change: worktree-checkout-existing-branch.
|
|
579
|
+
const baseIsLocalBranch =
|
|
580
|
+
checkoutMode && tryRun(`git show-ref --verify ${shellEscape(`refs/heads/${base}`)}`, cwd) !== undefined;
|
|
581
|
+
const resolvedBranch = checkoutMode
|
|
582
|
+
? resolveCheckoutLocalName(base, baseIsLocalBranch)
|
|
583
|
+
: newBranch;
|
|
584
|
+
// In checkout mode the commit-ish handed to git is the resolved local
|
|
585
|
+
// branch name (bare name triggers DWIM for remote-only refs); fork mode
|
|
586
|
+
// forks from `base`.
|
|
587
|
+
const checkoutCommitish = resolvedBranch;
|
|
588
|
+
// Resolve to the parent repo root (works whether cwd is the main checkout
|
|
589
|
+
// or any sibling worktree). `git rev-parse --show-toplevel` from a
|
|
590
|
+
// worktree returns the worktree's own root, NOT the main repo. We want
|
|
591
|
+
// the MAIN repo so `.worktrees/<slug>` lands consistently regardless of
|
|
592
|
+
// which worktree opened the dialog. Read `--git-common-dir` and walk up.
|
|
593
|
+
const commonDirRaw = tryRun("git rev-parse --git-common-dir", cwd);
|
|
594
|
+
if (!commonDirRaw) {
|
|
595
|
+
return { ok: false, error: "not_a_repo", message: "unable to resolve git common-dir" };
|
|
596
|
+
}
|
|
597
|
+
const commonDirAbs = path.isAbsolute(commonDirRaw)
|
|
598
|
+
? commonDirRaw
|
|
599
|
+
: path.resolve(cwd, commonDirRaw);
|
|
600
|
+
const repoRoot = path.dirname(commonDirAbs);
|
|
601
|
+
|
|
602
|
+
// Derive worktree path when not supplied. Fork mode slugs the new
|
|
603
|
+
// branch name; checkout mode slugs the local name of the base ref so
|
|
604
|
+
// `origin/foo` lands at `.worktrees/foo`, not `.worktrees/origin-foo`.
|
|
605
|
+
let worktreePath = opts.path;
|
|
606
|
+
if (!worktreePath) {
|
|
607
|
+
const slug = slugifyBranch(resolvedBranch);
|
|
608
|
+
if (!slug) {
|
|
609
|
+
return {
|
|
610
|
+
ok: false,
|
|
611
|
+
error: "git_failed",
|
|
612
|
+
message: `cannot derive a filesystem-safe slug from branch name "${resolvedBranch}"`,
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
worktreePath = path.join(repoRoot, ".worktrees", slug);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// Pre-flight: path must not exist (or must be empty).
|
|
619
|
+
if (fs.existsSync(worktreePath)) {
|
|
620
|
+
const isEmpty = (() => {
|
|
621
|
+
try { return fs.readdirSync(worktreePath).length === 0; } catch { return false; }
|
|
622
|
+
})();
|
|
623
|
+
if (!isEmpty) {
|
|
624
|
+
const orphanLikely = computeOrphanLikely(cwd, worktreePath);
|
|
625
|
+
return {
|
|
626
|
+
ok: false,
|
|
627
|
+
error: "path_exists",
|
|
628
|
+
message: `target path already exists and is not empty: ${worktreePath}`,
|
|
629
|
+
orphanLikely,
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// Fork mode: git worktree add -b <newBranch> <path> <base>
|
|
635
|
+
// Checkout mode: git worktree add <path> <commit-ish> (no -b)
|
|
636
|
+
// Args are quoted via single-shell-arg escaping below.
|
|
637
|
+
const args = ["git", "worktree", "add"];
|
|
638
|
+
if (force) args.push("--force");
|
|
639
|
+
if (!checkoutMode) args.push("-b", newBranch);
|
|
640
|
+
args.push(worktreePath, checkoutMode ? checkoutCommitish : base);
|
|
641
|
+
const cmd = args.map(shellEscape).join(" ");
|
|
642
|
+
try {
|
|
643
|
+
execSync(cmd, {
|
|
644
|
+
cwd,
|
|
645
|
+
encoding: "utf-8",
|
|
646
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
647
|
+
timeout: GIT_TIMEOUT,
|
|
648
|
+
});
|
|
649
|
+
} catch (err: any) {
|
|
650
|
+
const stderr = String(err?.stderr ?? err?.message ?? "");
|
|
651
|
+
// Map common stderr patterns onto stable error codes. The exact
|
|
652
|
+
// wording varies by git version; we match generously.
|
|
653
|
+
if (/already used by worktree at|is already checked out at/i.test(stderr)) {
|
|
654
|
+
// Enrich with the holding-worktree path when git exposes it, so the
|
|
655
|
+
// UI can render a clear inline error pointing at the conflict.
|
|
656
|
+
// See change: worktree-checkout-existing-branch.
|
|
657
|
+
const held = stderr.match(/already used by worktree at '([^']+)'/i)?.[1];
|
|
658
|
+
const message = held
|
|
659
|
+
? `branch is already checked out in another worktree at '${held}'`
|
|
660
|
+
: "branch is already checked out in another worktree";
|
|
661
|
+
return { ok: false, error: "branch_in_use", message, stderr };
|
|
662
|
+
}
|
|
663
|
+
if (/A branch named.*already exists|branch '.*' already exists/i.test(stderr)) {
|
|
664
|
+
return { ok: false, error: "branch_exists", message: `branch "${resolvedBranch}" already exists`, stderr };
|
|
665
|
+
}
|
|
666
|
+
if (/invalid reference|unknown revision|not a valid object name/i.test(stderr)) {
|
|
667
|
+
return { ok: false, error: "base_not_found", message: `base ref not found: ${base}`, stderr };
|
|
668
|
+
}
|
|
669
|
+
if (/'.*' already exists/i.test(stderr)) {
|
|
670
|
+
const orphanLikely = computeOrphanLikely(cwd, worktreePath);
|
|
671
|
+
return { ok: false, error: "path_exists", message: `target path already exists: ${worktreePath}`, stderr, orphanLikely };
|
|
672
|
+
}
|
|
673
|
+
return { ok: false, error: "git_failed", message: "git worktree add failed", stderr };
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Append `.worktrees/` to .git/info/exclude (idempotent). ONLY do this
|
|
677
|
+
// when we derived the path — if the user supplied an explicit `path`
|
|
678
|
+
// they're opting out of the convention.
|
|
679
|
+
let excludeAppended = false;
|
|
680
|
+
if (!opts.path) {
|
|
681
|
+
const excludePath = path.join(commonDirAbs, "info", "exclude");
|
|
682
|
+
try {
|
|
683
|
+
const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, "utf-8") : "";
|
|
684
|
+
const result = ensureWorktreeExcludeLine(existing);
|
|
685
|
+
if (result.appended) {
|
|
686
|
+
fs.mkdirSync(path.dirname(excludePath), { recursive: true });
|
|
687
|
+
fs.writeFileSync(excludePath, result.content);
|
|
688
|
+
excludeAppended = true;
|
|
689
|
+
}
|
|
690
|
+
} catch (err) {
|
|
691
|
+
// Non-fatal: the worktree is created; exclude write is housekeeping.
|
|
692
|
+
console.error(`[git-worktree] failed to update .git/info/exclude:`, err);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// Rewrite the new worktree's `.pi/settings.json` so any relative
|
|
697
|
+
// `packages[].source` paths resolve against the MAIN repo root instead
|
|
698
|
+
// of the worktree's own root. Without this, a worktree of an older
|
|
699
|
+
// branch loads pi packages (e.g. the dashboard bridge) from its own
|
|
700
|
+
// stale sibling directory — missing features that ship in the main
|
|
701
|
+
// repo's `feature/...` branch. Best-effort, non-fatal.
|
|
702
|
+
// See change: add-worktree-spawn-dialog.
|
|
703
|
+
rewriteWorktreePiSettings(worktreePath, repoRoot);
|
|
704
|
+
|
|
705
|
+
return { ok: true, path: worktreePath, branch: resolvedBranch, excludeAppended };
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Rewrite `<worktreePath>/.pi/settings.json` so any relative
|
|
710
|
+
* `packages[].source` becomes an absolute path against `mainRoot`.
|
|
711
|
+
*
|
|
712
|
+
* Idempotent and conservative:
|
|
713
|
+
* - If the file doesn't exist, do nothing (no template-fabrication).
|
|
714
|
+
* - If `packages` is absent or empty, do nothing.
|
|
715
|
+
* - Sources that are already absolute paths are left untouched.
|
|
716
|
+
* - Sources that look like URLs (`http://...`, `git+...`) or npm specs
|
|
717
|
+
* (no path separators / no `..`) are left untouched.
|
|
718
|
+
* - Only relative paths (`..`, `./...`, `../...`) are rewritten.
|
|
719
|
+
*
|
|
720
|
+
* Atomic write (write-to-tmp + rename).
|
|
721
|
+
*/
|
|
722
|
+
export function rewriteWorktreePiSettings(worktreePath: string, mainRoot: string): void {
|
|
723
|
+
const settingsPath = path.join(worktreePath, ".pi", "settings.json");
|
|
724
|
+
let raw: string;
|
|
725
|
+
try {
|
|
726
|
+
raw = fs.readFileSync(settingsPath, "utf-8");
|
|
727
|
+
} catch {
|
|
728
|
+
// No project settings in the worktree — nothing to rewrite.
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
let parsed: { packages?: Array<{ source?: string; [k: string]: unknown }>; [k: string]: unknown };
|
|
732
|
+
try {
|
|
733
|
+
parsed = JSON.parse(raw);
|
|
734
|
+
} catch (err) {
|
|
735
|
+
console.error(`[git-worktree] worktree .pi/settings.json is malformed; skipping rewrite:`, err);
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const packages = Array.isArray(parsed.packages) ? parsed.packages : [];
|
|
739
|
+
if (packages.length === 0) return;
|
|
740
|
+
let changed = false;
|
|
741
|
+
for (const pkg of packages) {
|
|
742
|
+
if (typeof pkg.source !== "string") continue;
|
|
743
|
+
if (!isRelativePathSource(pkg.source)) continue;
|
|
744
|
+
// Source resolves relative to the .pi directory by pi's convention
|
|
745
|
+
// (i.e. `..` from `.pi/` is the project root). We want it to resolve
|
|
746
|
+
// against the MAIN repo's `.pi/`, so we anchor against `<mainRoot>/.pi`.
|
|
747
|
+
const anchorDir = path.join(mainRoot, ".pi");
|
|
748
|
+
const absolute = path.resolve(anchorDir, pkg.source);
|
|
749
|
+
pkg.source = absolute;
|
|
750
|
+
changed = true;
|
|
751
|
+
}
|
|
752
|
+
if (!changed) return;
|
|
753
|
+
try {
|
|
754
|
+
const tmpPath = settingsPath + ".tmp";
|
|
755
|
+
fs.writeFileSync(tmpPath, JSON.stringify(parsed, null, 2) + "\n");
|
|
756
|
+
fs.renameSync(tmpPath, settingsPath);
|
|
757
|
+
} catch (err) {
|
|
758
|
+
console.error(`[git-worktree] failed to write rewritten .pi/settings.json:`, err);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* True when `source` is a relative filesystem path (`..`, `./...`,
|
|
764
|
+
* `../...`, or a bare relative segment). Absolute paths, URLs, and npm
|
|
765
|
+
* package specs are NOT considered relative.
|
|
766
|
+
*/
|
|
767
|
+
function isRelativePathSource(source: string): boolean {
|
|
768
|
+
if (source.length === 0) return false;
|
|
769
|
+
if (path.isAbsolute(source)) return false;
|
|
770
|
+
// URL-like: http(s)://, git+ssh://, file://, ssh://, etc. Match any
|
|
771
|
+
// scheme made of [a-z0-9+.-] followed by `://`.
|
|
772
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(source)) return false;
|
|
773
|
+
// Scoped npm package: `@scope/name`. Stays untouched.
|
|
774
|
+
if (/^@[^/\\]+\/[^/\\]+$/.test(source)) return false;
|
|
775
|
+
if (source.startsWith(".") || source.startsWith("..")) return true;
|
|
776
|
+
// A bare name (e.g. "foo") could be an npm package spec or a relative
|
|
777
|
+
// directory. We conservatively treat path-separator-bearing names as
|
|
778
|
+
// relative paths; pure single segments as npm.
|
|
779
|
+
return source.includes("/") || source.includes("\\");
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/**
|
|
783
|
+
* Single-arg shell-escape helper. Sufficient for the path / branch /
|
|
784
|
+
* base values we pass; we never interpolate user-controlled shell
|
|
785
|
+
* fragments. Wraps in single quotes and escapes embedded single quotes.
|
|
786
|
+
*/
|
|
787
|
+
function shellEscape(arg: string): string {
|
|
788
|
+
return `'${arg.replace(/'/g, "'\\''")}'`;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// ── Worktree lifecycle (remove / merge / push / pr) ─────────────────────────
|
|
792
|
+
// See change: add-worktree-lifecycle-actions.
|
|
793
|
+
|
|
794
|
+
import {
|
|
795
|
+
type MergeCode,
|
|
796
|
+
mapMergeStderr,
|
|
797
|
+
mapPrStderr,
|
|
798
|
+
mapPushStderr,
|
|
799
|
+
mapRemoveStderr,
|
|
800
|
+
type PrCode,
|
|
801
|
+
type PushCode,
|
|
802
|
+
parsePrUrl,
|
|
803
|
+
parseShortstat,
|
|
804
|
+
type RemoveCode,
|
|
805
|
+
} from "./git-worktree-lifecycle.js";
|
|
806
|
+
|
|
807
|
+
export interface LifecycleSuccess<T = unknown> {
|
|
808
|
+
ok: true;
|
|
809
|
+
data?: T;
|
|
810
|
+
}
|
|
811
|
+
export interface LifecycleFailure<C extends string = string> {
|
|
812
|
+
ok: false;
|
|
813
|
+
code: C;
|
|
814
|
+
stderr?: string;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* Resolve the main checkout (parent repo root) for any `cwd`. Returns
|
|
819
|
+
* `null` when the cwd isn't a git work tree.
|
|
820
|
+
*/
|
|
821
|
+
export function resolveMainPath(cwd: string): string | null {
|
|
822
|
+
const commonDirRaw = tryRun("git rev-parse --git-common-dir", cwd);
|
|
823
|
+
if (!commonDirRaw) return null;
|
|
824
|
+
const commonDirAbs = path.isAbsolute(commonDirRaw)
|
|
825
|
+
? commonDirRaw
|
|
826
|
+
: path.resolve(cwd, commonDirRaw);
|
|
827
|
+
return path.dirname(commonDirAbs);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Resolve the directory that holds config (`.pi/settings.json`) for `cwd`,
|
|
832
|
+
* without assuming git. Used only by the worktree init-status / init routes
|
|
833
|
+
* so a declared hook is readable in a non-git directory.
|
|
834
|
+
*
|
|
835
|
+
* - git repo / worktree → `resolveMainPath(cwd)` (unchanged; may be `null` for a
|
|
836
|
+
* degenerate git state). A git dir is NEVER treated as its own config root —
|
|
837
|
+
* the non-git `cwd/.pi` branch is reachable only when `isGitRepo` is false.
|
|
838
|
+
* - non-git dir with `.pi/settings.json` → `cwd` itself (no upward walk).
|
|
839
|
+
* - non-git dir without it → `null`.
|
|
840
|
+
*
|
|
841
|
+
* See change: support-non-git-init-hook.
|
|
842
|
+
*/
|
|
843
|
+
export function resolveConfigRoot(cwd: string): string | null {
|
|
844
|
+
if (self.isGitRepo(cwd)) return self.resolveMainPath(cwd);
|
|
845
|
+
return fs.existsSync(path.join(cwd, ".pi", "settings.json")) ? cwd : null;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* Guarded residual-dir sweep. Deletes a leftover physical directory at a
|
|
850
|
+
* removed worktree path ONLY when every safety condition holds:
|
|
851
|
+
* - the path exists on disk (else no-op → `false`);
|
|
852
|
+
* - its resolved realpath is strictly INSIDE `<mainPath>/.worktrees/`
|
|
853
|
+
* (symlink-resolved via the parent dir + basename, so a symlinked
|
|
854
|
+
* `.worktrees/<name>` pointing outside cannot escape the subtree);
|
|
855
|
+
* - it is not the `.worktrees/` root itself and never the main checkout.
|
|
856
|
+
*
|
|
857
|
+
* Returns `true` when a directory was removed, `false` on any refusal or
|
|
858
|
+
* no-op. Destructive by design — the guard is the core safety control.
|
|
859
|
+
* See change: sweep-worktree-residual-on-remove.
|
|
860
|
+
*/
|
|
861
|
+
export function sweepResidualWorktreeDir(mainPath: string, cwd: string): boolean {
|
|
862
|
+
if (!fs.existsSync(cwd)) return false;
|
|
863
|
+
const worktreesRoot = path.join(mainPath, ".worktrees");
|
|
864
|
+
// Resolve symlinks. The target may itself be a symlink, so resolve its
|
|
865
|
+
// PARENT dir (real) + append the basename, then realpath the whole thing
|
|
866
|
+
// when it resolves to a real entry. This defeats a symlinked leaf that
|
|
867
|
+
// points outside the subtree.
|
|
868
|
+
let realTarget: string;
|
|
869
|
+
let realRoot: string;
|
|
870
|
+
try {
|
|
871
|
+
realTarget = fs.realpathSync(cwd);
|
|
872
|
+
if (!fs.existsSync(worktreesRoot)) return false;
|
|
873
|
+
realRoot = fs.realpathSync(worktreesRoot);
|
|
874
|
+
} catch {
|
|
875
|
+
return false;
|
|
876
|
+
}
|
|
877
|
+
const realMain = (() => {
|
|
878
|
+
try { return fs.realpathSync(mainPath); } catch { return path.resolve(mainPath); }
|
|
879
|
+
})();
|
|
880
|
+
// Never the main checkout, never the .worktrees root.
|
|
881
|
+
if (realTarget === realMain || realTarget === realRoot) return false;
|
|
882
|
+
// Must be strictly inside the .worktrees/ subtree.
|
|
883
|
+
const rootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;
|
|
884
|
+
if (!realTarget.startsWith(rootWithSep)) return false;
|
|
885
|
+
try {
|
|
886
|
+
fs.rmSync(realTarget, { recursive: true, force: true });
|
|
887
|
+
} catch {
|
|
888
|
+
return false;
|
|
889
|
+
}
|
|
890
|
+
return true;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* `git worktree remove [--force] <cwd>` invoked from the parent repo.
|
|
895
|
+
* Stderr is mapped to a stable code.
|
|
896
|
+
*
|
|
897
|
+
* On git-confirmed removal, sweeps any residual physical directory that
|
|
898
|
+
* survives at the worktree path (a kb husk recreated during removal) —
|
|
899
|
+
* hard-guarded to the parent repo's `.worktrees/` subtree. Never runs on a
|
|
900
|
+
* git failure. See change: sweep-worktree-residual-on-remove.
|
|
901
|
+
*/
|
|
902
|
+
export function removeWorktree(opts: {
|
|
903
|
+
cwd: string;
|
|
904
|
+
force?: boolean;
|
|
905
|
+
}): LifecycleSuccess<{ removed: true }> | LifecycleFailure<RemoveCode> {
|
|
906
|
+
const { cwd, force } = opts;
|
|
907
|
+
const mainPath = resolveMainPath(cwd);
|
|
908
|
+
if (!mainPath) return { ok: false, code: "not_a_worktree" };
|
|
909
|
+
const args = ["git", "worktree", "remove"];
|
|
910
|
+
if (force) args.push("--force");
|
|
911
|
+
args.push(cwd);
|
|
912
|
+
try {
|
|
913
|
+
execSync(args.map(shellEscape).join(" "), {
|
|
914
|
+
cwd: mainPath,
|
|
915
|
+
encoding: "utf-8",
|
|
916
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
917
|
+
timeout: GIT_TIMEOUT,
|
|
918
|
+
});
|
|
919
|
+
} catch (err: any) {
|
|
920
|
+
const stderr = String(err?.stderr ?? err?.message ?? "");
|
|
921
|
+
return { ok: false, code: mapRemoveStderr(stderr), stderr };
|
|
922
|
+
}
|
|
923
|
+
// Belt-and-suspenders: git reported success but a live kb handle may have
|
|
924
|
+
// recreated the dir. Sweep it, guarded to `.worktrees/`.
|
|
925
|
+
sweepResidualWorktreeDir(mainPath, cwd);
|
|
926
|
+
return { ok: true, data: { removed: true } };
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
const BASE_FALLBACKS = ["develop", "main", "master"] as const;
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Resolve the base ref for a merge: prefer the explicit `gitWorktreeBase`,
|
|
933
|
+
* else first match in `develop|main|master` (local then `origin/`).
|
|
934
|
+
*/
|
|
935
|
+
export function resolveDefaultBase(
|
|
936
|
+
cwd: string,
|
|
937
|
+
hint?: string,
|
|
938
|
+
): string | null {
|
|
939
|
+
if (hint && tryRun(`git rev-parse --verify ${shellEscape(hint)}`, cwd)) return hint;
|
|
940
|
+
for (const name of BASE_FALLBACKS) {
|
|
941
|
+
if (tryRun(`git rev-parse --verify refs/heads/${name}`, cwd)) return name;
|
|
942
|
+
}
|
|
943
|
+
for (const name of BASE_FALLBACKS) {
|
|
944
|
+
if (tryRun(`git rev-parse --verify refs/remotes/origin/${name}`, cwd)) {
|
|
945
|
+
return `origin/${name}`;
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
return null;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* Resolve the PR base for `gh pr create`. Differs from `resolveDefaultBase`
|
|
953
|
+
* in two ways:
|
|
954
|
+
* 1. The hint MUST exist on `origin/` (`refs/remotes/origin/<hint>`).
|
|
955
|
+
* `gh pr create` needs the base to be a remote branch — a local-only
|
|
956
|
+
* hint (e.g. a feature branch the worktree forked from but that was
|
|
957
|
+
* never pushed) is rejected here and the chain falls through to the
|
|
958
|
+
* `develop|main|master` fallbacks on `origin/`.
|
|
959
|
+
* 2. Returns the bare branch name (no `origin/` prefix), since `gh` wants
|
|
960
|
+
* `--base <name>` not `--base origin/<name>`.
|
|
961
|
+
*
|
|
962
|
+
* See change: add-worktree-lifecycle-actions.
|
|
963
|
+
*/
|
|
964
|
+
export function resolveRemoteBase(
|
|
965
|
+
cwd: string,
|
|
966
|
+
hint?: string,
|
|
967
|
+
): string | null {
|
|
968
|
+
const stripOrigin = (n: string) => n.replace(/^origin\//, "");
|
|
969
|
+
const hintBare = hint ? stripOrigin(hint) : undefined;
|
|
970
|
+
if (hintBare && tryRun(`git rev-parse --verify refs/remotes/origin/${shellEscape(hintBare)}`, cwd)) {
|
|
971
|
+
return hintBare;
|
|
972
|
+
}
|
|
973
|
+
for (const name of BASE_FALLBACKS) {
|
|
974
|
+
if (tryRun(`git rev-parse --verify refs/remotes/origin/${name}`, cwd)) {
|
|
975
|
+
return name;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return null;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/**
|
|
982
|
+
* Merge the worktree's current branch into its base ref. Refuses when
|
|
983
|
+
* the main checkout is dirty; aborts the merge on conflict.
|
|
984
|
+
*
|
|
985
|
+
* Steps (all in `mainPath`):
|
|
986
|
+
* 1. `git status --porcelain` (empty => clean)
|
|
987
|
+
* 2. `git checkout <base>`
|
|
988
|
+
* 3. `git merge --no-ff <branch>`
|
|
989
|
+
* 4. Optional `git branch -d <branch>`
|
|
990
|
+
*/
|
|
991
|
+
export function mergeWorktree(opts: {
|
|
992
|
+
cwd: string;
|
|
993
|
+
baseHint?: string;
|
|
994
|
+
deleteBranch?: boolean;
|
|
995
|
+
}): LifecycleSuccess<{ mergeSha: string; branchDeleted: boolean }> | LifecycleFailure<MergeCode | "dirty_main"> {
|
|
996
|
+
const { cwd, baseHint, deleteBranch } = opts;
|
|
997
|
+
const mainPath = resolveMainPath(cwd);
|
|
998
|
+
if (!mainPath) return { ok: false, code: "git_failed", stderr: "unable to resolve main checkout" };
|
|
999
|
+
const branch = tryRun("git rev-parse --abbrev-ref HEAD", cwd);
|
|
1000
|
+
if (!branch || branch === "HEAD") {
|
|
1001
|
+
return { ok: false, code: "git_failed", stderr: "worktree is in a detached HEAD state" };
|
|
1002
|
+
}
|
|
1003
|
+
const base = resolveDefaultBase(mainPath, baseHint);
|
|
1004
|
+
if (!base) return { ok: false, code: "base_not_found" };
|
|
1005
|
+
|
|
1006
|
+
// 1. Main must be clean.
|
|
1007
|
+
const porcelain = tryRun("git status --porcelain", mainPath);
|
|
1008
|
+
if (porcelain && porcelain.length > 0) {
|
|
1009
|
+
return { ok: false, code: "dirty_main" as any, stderr: porcelain };
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// 2. Checkout base in main.
|
|
1013
|
+
try {
|
|
1014
|
+
execSync(`git checkout ${shellEscape(base)}`, {
|
|
1015
|
+
cwd: mainPath,
|
|
1016
|
+
encoding: "utf-8",
|
|
1017
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1018
|
+
timeout: GIT_TIMEOUT,
|
|
1019
|
+
});
|
|
1020
|
+
} catch (err: any) {
|
|
1021
|
+
const stderr = String(err?.stderr ?? err?.message ?? "");
|
|
1022
|
+
return { ok: false, code: mapMergeStderr(stderr), stderr };
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
// 3. Merge --no-ff.
|
|
1026
|
+
try {
|
|
1027
|
+
execSync(`git merge --no-ff ${shellEscape(branch)}`, {
|
|
1028
|
+
cwd: mainPath,
|
|
1029
|
+
encoding: "utf-8",
|
|
1030
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1031
|
+
timeout: GIT_TIMEOUT,
|
|
1032
|
+
});
|
|
1033
|
+
} catch (err: any) {
|
|
1034
|
+
// git writes conflict notices to BOTH stdout ("CONFLICT (content)...")
|
|
1035
|
+
// AND stderr ("Automatic merge failed..."). Concatenate so the mapper
|
|
1036
|
+
// sees all of it; empty strings are harmless.
|
|
1037
|
+
const stderrRaw = [err?.stderr, err?.stdout, err?.message]
|
|
1038
|
+
.map((v) => (v == null ? "" : String(v)))
|
|
1039
|
+
.filter((s) => s.length > 0)
|
|
1040
|
+
.join("\n");
|
|
1041
|
+
const code = mapMergeStderr(stderrRaw);
|
|
1042
|
+
if (code === "merge_conflict") {
|
|
1043
|
+
// Best-effort abort to leave main on `base` in a clean state.
|
|
1044
|
+
tryRun("git merge --abort", mainPath);
|
|
1045
|
+
}
|
|
1046
|
+
return { ok: false, code, stderr: stderrRaw };
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const mergeSha = tryRun("git rev-parse --short HEAD", mainPath) ?? "";
|
|
1050
|
+
|
|
1051
|
+
let branchDeleted = false;
|
|
1052
|
+
if (deleteBranch) {
|
|
1053
|
+
try {
|
|
1054
|
+
execSync(`git branch -d ${shellEscape(branch)}`, {
|
|
1055
|
+
cwd: mainPath,
|
|
1056
|
+
encoding: "utf-8",
|
|
1057
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1058
|
+
timeout: GIT_TIMEOUT,
|
|
1059
|
+
});
|
|
1060
|
+
branchDeleted = true;
|
|
1061
|
+
} catch {
|
|
1062
|
+
// Refuse to escalate to -D — the spec explicitly forbids it.
|
|
1063
|
+
branchDeleted = false;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
return { ok: true, data: { mergeSha, branchDeleted } };
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
/**
|
|
1071
|
+
* Five-line `git diff --stat <base>..<branch>` plus shortstat numbers,
|
|
1072
|
+
* for the merge confirm dialog.
|
|
1073
|
+
*/
|
|
1074
|
+
export function worktreeDiffStat(opts: {
|
|
1075
|
+
cwd: string;
|
|
1076
|
+
baseHint?: string;
|
|
1077
|
+
}): LifecycleSuccess<{ summary: string; filesChanged: number; insertions: number; deletions: number; base: string; branch: string }> | LifecycleFailure<MergeCode> {
|
|
1078
|
+
const { cwd, baseHint } = opts;
|
|
1079
|
+
const mainPath = resolveMainPath(cwd);
|
|
1080
|
+
if (!mainPath) return { ok: false, code: "git_failed" };
|
|
1081
|
+
const branch = tryRun("git rev-parse --abbrev-ref HEAD", cwd);
|
|
1082
|
+
if (!branch || branch === "HEAD") return { ok: false, code: "git_failed" };
|
|
1083
|
+
const base = resolveDefaultBase(mainPath, baseHint);
|
|
1084
|
+
if (!base) return { ok: false, code: "base_not_found" };
|
|
1085
|
+
let stat: string;
|
|
1086
|
+
try {
|
|
1087
|
+
stat = execSync(
|
|
1088
|
+
`git diff --stat ${shellEscape(base)}..${shellEscape(branch)}`,
|
|
1089
|
+
{ cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], timeout: GIT_TIMEOUT },
|
|
1090
|
+
);
|
|
1091
|
+
} catch (err: any) {
|
|
1092
|
+
const stderr = String(err?.stderr ?? err?.message ?? "");
|
|
1093
|
+
return { ok: false, code: mapMergeStderr(stderr), stderr };
|
|
1094
|
+
}
|
|
1095
|
+
const lines = stat.split("\n").filter((l) => l.length > 0);
|
|
1096
|
+
const summary = lines.slice(0, 5).join("\n");
|
|
1097
|
+
const shortstatLine = lines[lines.length - 1] ?? "";
|
|
1098
|
+
const { filesChanged, insertions, deletions } = parseShortstat(shortstatLine);
|
|
1099
|
+
return {
|
|
1100
|
+
ok: true,
|
|
1101
|
+
data: { summary, filesChanged, insertions, deletions, base, branch },
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/**
|
|
1106
|
+
* `git push [-u] origin <branch>` from the worktree.
|
|
1107
|
+
*/
|
|
1108
|
+
export function pushBranch(opts: {
|
|
1109
|
+
cwd: string;
|
|
1110
|
+
setUpstream?: boolean;
|
|
1111
|
+
}): LifecycleSuccess<{ pushed: true }> | LifecycleFailure<PushCode> {
|
|
1112
|
+
const { cwd, setUpstream = true } = opts;
|
|
1113
|
+
const branch = tryRun("git rev-parse --abbrev-ref HEAD", cwd);
|
|
1114
|
+
if (!branch || branch === "HEAD") {
|
|
1115
|
+
return { ok: false, code: "git_failed", stderr: "detached HEAD" };
|
|
1116
|
+
}
|
|
1117
|
+
// Detect missing remote up-front for a clean error.
|
|
1118
|
+
const remoteExists = tryRun("git remote get-url origin", cwd);
|
|
1119
|
+
if (!remoteExists) return { ok: false, code: "no_remote" };
|
|
1120
|
+
const args = ["git", "push"];
|
|
1121
|
+
if (setUpstream) args.push("-u");
|
|
1122
|
+
args.push("origin", branch);
|
|
1123
|
+
try {
|
|
1124
|
+
execSync(args.map(shellEscape).join(" "), {
|
|
1125
|
+
cwd,
|
|
1126
|
+
encoding: "utf-8",
|
|
1127
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1128
|
+
timeout: GIT_TIMEOUT,
|
|
1129
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
1130
|
+
});
|
|
1131
|
+
} catch (err: any) {
|
|
1132
|
+
const stderr = String(err?.stderr ?? err?.message ?? "");
|
|
1133
|
+
return { ok: false, code: mapPushStderr(stderr), stderr };
|
|
1134
|
+
}
|
|
1135
|
+
return { ok: true, data: { pushed: true } };
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
/**
|
|
1139
|
+
* Open a GitHub pull request via `gh pr create`. When the branch has
|
|
1140
|
+
* no upstream, push first. Caller is expected to have resolved `gh`
|
|
1141
|
+
* via the tool registry (we accept the path here).
|
|
1142
|
+
*/
|
|
1143
|
+
export function createPullRequest(opts: {
|
|
1144
|
+
cwd: string;
|
|
1145
|
+
ghPath: string;
|
|
1146
|
+
title?: string;
|
|
1147
|
+
body?: string;
|
|
1148
|
+
baseHint?: string;
|
|
1149
|
+
}): LifecycleSuccess<{ url: string; pushed: boolean }> | LifecycleFailure<PrCode | PushCode | "pushed_but_pr_failed"> {
|
|
1150
|
+
const { cwd, ghPath, title, body, baseHint } = opts;
|
|
1151
|
+
const branch = tryRun("git rev-parse --abbrev-ref HEAD", cwd);
|
|
1152
|
+
if (!branch || branch === "HEAD") {
|
|
1153
|
+
return { ok: false, code: "git_failed", stderr: "detached HEAD" };
|
|
1154
|
+
}
|
|
1155
|
+
const upstream = tryRun(`git rev-parse --abbrev-ref ${shellEscape(branch)}@{upstream}`, cwd);
|
|
1156
|
+
let pushed = false;
|
|
1157
|
+
if (!upstream) {
|
|
1158
|
+
const pushResult = pushBranch({ cwd, setUpstream: true });
|
|
1159
|
+
if (!pushResult.ok) return pushResult;
|
|
1160
|
+
pushed = true;
|
|
1161
|
+
}
|
|
1162
|
+
const mainPath = resolveMainPath(cwd);
|
|
1163
|
+
// Resolve base AGAINST `origin/` because `gh pr create` needs a remote
|
|
1164
|
+
// branch (it diffs origin/<base>..<head> to populate --fill or to
|
|
1165
|
+
// validate the PR). Falls back to `origin/{develop,main,master}` when
|
|
1166
|
+
// the session's `gitWorktreeBase` hint is a local-only branch.
|
|
1167
|
+
const base = resolveRemoteBase(cwd, baseHint);
|
|
1168
|
+
if (!base) return { ok: false, code: "base_not_found", stderr: `no base branch found on origin (tried hint=${baseHint ?? "<none>"} + ${BASE_FALLBACKS.join("|")})` };
|
|
1169
|
+
const args = [ghPath, "pr", "create", "--base", base, "--head", branch];
|
|
1170
|
+
// Derive an explicit title when none supplied. Using `--fill` requires
|
|
1171
|
+
// the remote base ref to be locally up-to-date so gh can compute the
|
|
1172
|
+
// diff; on freshly-pushed branches that's often not true and --fill
|
|
1173
|
+
// explodes with "could not compute title or body defaults: failed to
|
|
1174
|
+
// run git: fatal: ambiguous argument ...". Falling back to the latest
|
|
1175
|
+
// commit subject (or branch name) side-steps the dependency on origin.
|
|
1176
|
+
const resolvedTitle = title ?? deriveDefaultPrTitle(cwd, branch);
|
|
1177
|
+
args.push("--title", resolvedTitle);
|
|
1178
|
+
args.push("--body", body ?? "");
|
|
1179
|
+
let stdout: string;
|
|
1180
|
+
try {
|
|
1181
|
+
stdout = execSync(args.map(shellEscape).join(" "), {
|
|
1182
|
+
cwd,
|
|
1183
|
+
encoding: "utf-8",
|
|
1184
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1185
|
+
timeout: GIT_TIMEOUT,
|
|
1186
|
+
env: { ...process.env, GH_PROMPT_DISABLED: "1" },
|
|
1187
|
+
});
|
|
1188
|
+
} catch (err: any) {
|
|
1189
|
+
// gh writes the error to BOTH stdout and stderr in many failure
|
|
1190
|
+
// modes (e.g. "could not compute title or body defaults" lands on
|
|
1191
|
+
// stdout). Concatenate so the mapper sees all of it.
|
|
1192
|
+
const stderr = [err?.stderr, err?.stdout, err?.message]
|
|
1193
|
+
.map((v) => (v == null ? "" : String(v)))
|
|
1194
|
+
.filter((s) => s.length > 0)
|
|
1195
|
+
.join("\n");
|
|
1196
|
+
const code = mapPrStderr(stderr);
|
|
1197
|
+
if (pushed) {
|
|
1198
|
+
return { ok: false, code: "pushed_but_pr_failed", stderr };
|
|
1199
|
+
}
|
|
1200
|
+
return { ok: false, code, stderr };
|
|
1201
|
+
}
|
|
1202
|
+
const url = parsePrUrl(stdout);
|
|
1203
|
+
if (!url) {
|
|
1204
|
+
return { ok: false, code: "git_failed", stderr: stdout };
|
|
1205
|
+
}
|
|
1206
|
+
return { ok: true, data: { url, pushed } };
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/**
|
|
1210
|
+
* Default PR title when the caller doesn't supply one. Prefers the
|
|
1211
|
+
* latest commit subject on `branch`; falls back to the branch name.
|
|
1212
|
+
* Trimmed and truncated to 72 chars (conventional PR title limit).
|
|
1213
|
+
*/
|
|
1214
|
+
function deriveDefaultPrTitle(cwd: string, branch: string): string {
|
|
1215
|
+
const subject = tryRun(`git log -1 --format=%s ${shellEscape(branch)}`, cwd);
|
|
1216
|
+
const candidate = (subject && subject.length > 0) ? subject : branch;
|
|
1217
|
+
return candidate.slice(0, 72);
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/** Pop the most recent stash. */
|
|
1221
|
+
export function stashPop(cwd: string): StashPopResult {
|
|
1222
|
+
// Check if there are stash entries
|
|
1223
|
+
const stashList = tryRun("git stash list", cwd);
|
|
1224
|
+
if (!stashList) {
|
|
1225
|
+
throw new Error("no stash entries");
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
try {
|
|
1229
|
+
run("git stash pop", cwd);
|
|
1230
|
+
return { conflicts: false };
|
|
1231
|
+
} catch (err: any) {
|
|
1232
|
+
// git stash pop exits non-zero on conflicts but still applies
|
|
1233
|
+
const msg: string = [err.stdout, err.stderr, err.message].filter(Boolean).join("\n");
|
|
1234
|
+
if (msg.includes("CONFLICT") || msg.includes("conflict") || msg.includes("Merge conflict")) {
|
|
1235
|
+
return { conflicts: true };
|
|
1236
|
+
}
|
|
1237
|
+
throw err;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// ── orphan-path detection + cleanup (change: openspec-worktree-spawn-button) ──
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* Internal helper: returns `true` when `worktreePath` exists on disk but
|
|
1245
|
+
* is NOT a registered worktree of the repo at `cwd`. Used to populate the
|
|
1246
|
+
* `orphanLikely` field on `addWorktree`'s `path_exists` error envelope.
|
|
1247
|
+
*
|
|
1248
|
+
* Returns `false` on any error (defensive — if we can't compute, don't
|
|
1249
|
+
* promise the user a Clean-up affordance).
|
|
1250
|
+
*
|
|
1251
|
+
* See change: openspec-worktree-spawn-button.
|
|
1252
|
+
*/
|
|
1253
|
+
function computeOrphanLikely(cwd: string, worktreePath: string): boolean {
|
|
1254
|
+
try {
|
|
1255
|
+
const list = listWorktrees(cwd);
|
|
1256
|
+
return isOrphanWorktreePath({
|
|
1257
|
+
path: worktreePath,
|
|
1258
|
+
worktreeList: list,
|
|
1259
|
+
exists: (p: string) => fs.existsSync(p),
|
|
1260
|
+
});
|
|
1261
|
+
} catch {
|
|
1262
|
+
return false;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
export type OrphanCleanupError =
|
|
1267
|
+
| "outside_repo"
|
|
1268
|
+
| "not_a_directory"
|
|
1269
|
+
| "not_orphan"
|
|
1270
|
+
| "looks_like_worktree"
|
|
1271
|
+
| "too_many_files"
|
|
1272
|
+
| "file_too_large"
|
|
1273
|
+
| "fs_failed";
|
|
1274
|
+
|
|
1275
|
+
export interface OrphanCleanupSuccess {
|
|
1276
|
+
ok: true;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
export interface OrphanCleanupFailure {
|
|
1280
|
+
ok: false;
|
|
1281
|
+
error: OrphanCleanupError;
|
|
1282
|
+
message: string;
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
export interface OrphanCleanupOptions {
|
|
1286
|
+
/** Cwd of the parent repo (used to resolve repo root + worktree list). */
|
|
1287
|
+
cwd: string;
|
|
1288
|
+
/** Absolute path of the orphan directory to delete. */
|
|
1289
|
+
path: string;
|
|
1290
|
+
/** Maximum file count allowed in the orphan dir. Default 20. */
|
|
1291
|
+
maxFiles?: number;
|
|
1292
|
+
/** Maximum per-file size in bytes. Default 1 MB. */
|
|
1293
|
+
maxFileSize?: number;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* Conservatively delete an orphan worktree-path directory. This unblocks
|
|
1298
|
+
* `addWorktree` when a previous failed attempt left a non-empty dir at
|
|
1299
|
+
* the target path — git's worktree list doesn't know about it (so the
|
|
1300
|
+
* dialog's existing-worktree list never shows it), but the fs-level
|
|
1301
|
+
* collision check blocks creation.
|
|
1302
|
+
*
|
|
1303
|
+
* Refuses (with a stable error code) unless EVERY guard passes:
|
|
1304
|
+
* - `path` is inside `cwd` (anti-traversal)
|
|
1305
|
+
* - `path` exists and is a directory
|
|
1306
|
+
* - `path` is NOT in `git worktree list --porcelain` for `cwd`
|
|
1307
|
+
* - `path` does NOT contain a top-level `.git` entry (file or directory)
|
|
1308
|
+
* - file count is ≤ `maxFiles` (default 20)
|
|
1309
|
+
* - no file exceeds `maxFileSize` (default 1 MB)
|
|
1310
|
+
*
|
|
1311
|
+
* On pass: `fs.rmSync(path, {recursive: true, force: true})`.
|
|
1312
|
+
*
|
|
1313
|
+
* See change: openspec-worktree-spawn-button.
|
|
1314
|
+
*/
|
|
1315
|
+
export function orphanCleanup(
|
|
1316
|
+
opts: OrphanCleanupOptions,
|
|
1317
|
+
): OrphanCleanupSuccess | OrphanCleanupFailure {
|
|
1318
|
+
const { cwd } = opts;
|
|
1319
|
+
const targetPath = opts.path;
|
|
1320
|
+
const maxFiles = opts.maxFiles ?? 20;
|
|
1321
|
+
const maxFileSize = opts.maxFileSize ?? 1_048_576; // 1 MB
|
|
1322
|
+
|
|
1323
|
+
// Resolve repo root via git common-dir (works from any worktree).
|
|
1324
|
+
const commonDirRaw = tryRun("git rev-parse --git-common-dir", cwd);
|
|
1325
|
+
if (!commonDirRaw) {
|
|
1326
|
+
return { ok: false, error: "outside_repo", message: "cwd is not inside a git repository" };
|
|
1327
|
+
}
|
|
1328
|
+
const commonDirAbs = path.isAbsolute(commonDirRaw)
|
|
1329
|
+
? commonDirRaw
|
|
1330
|
+
: path.resolve(cwd, commonDirRaw);
|
|
1331
|
+
const repoRoot = path.dirname(commonDirAbs);
|
|
1332
|
+
|
|
1333
|
+
// Anti-traversal: `targetPath` MUST be inside repoRoot. We resolve both
|
|
1334
|
+
// and compare prefixes (with separator) to avoid `/repo` matching
|
|
1335
|
+
// `/repository`.
|
|
1336
|
+
const absTarget = path.resolve(targetPath);
|
|
1337
|
+
const absRoot = path.resolve(repoRoot);
|
|
1338
|
+
const rootWithSep = absRoot.endsWith(path.sep) ? absRoot : absRoot + path.sep;
|
|
1339
|
+
if (absTarget !== absRoot && !absTarget.startsWith(rootWithSep)) {
|
|
1340
|
+
return { ok: false, error: "outside_repo", message: `path is not inside repo root: ${absTarget}` };
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// Path must exist and be a directory.
|
|
1344
|
+
let stat;
|
|
1345
|
+
try {
|
|
1346
|
+
stat = fs.statSync(absTarget);
|
|
1347
|
+
} catch {
|
|
1348
|
+
return { ok: false, error: "not_a_directory", message: `path does not exist: ${absTarget}` };
|
|
1349
|
+
}
|
|
1350
|
+
if (!stat.isDirectory()) {
|
|
1351
|
+
return { ok: false, error: "not_a_directory", message: `path is not a directory: ${absTarget}` };
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
// Must NOT be a registered worktree.
|
|
1355
|
+
let isOrphan = false;
|
|
1356
|
+
try {
|
|
1357
|
+
const list = listWorktrees(cwd);
|
|
1358
|
+
isOrphan = isOrphanWorktreePath({
|
|
1359
|
+
path: absTarget,
|
|
1360
|
+
worktreeList: list,
|
|
1361
|
+
exists: () => true, // we already confirmed via statSync above
|
|
1362
|
+
});
|
|
1363
|
+
} catch {
|
|
1364
|
+
return { ok: false, error: "fs_failed", message: "failed to list worktrees" };
|
|
1365
|
+
}
|
|
1366
|
+
if (!isOrphan) {
|
|
1367
|
+
return { ok: false, error: "not_orphan", message: `path is a registered worktree: ${absTarget}` };
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// Must NOT contain a top-level `.git` entry of any kind.
|
|
1371
|
+
let topEntries: fs.Dirent[];
|
|
1372
|
+
try {
|
|
1373
|
+
topEntries = fs.readdirSync(absTarget, { withFileTypes: true });
|
|
1374
|
+
} catch {
|
|
1375
|
+
return { ok: false, error: "fs_failed", message: "failed to read directory" };
|
|
1376
|
+
}
|
|
1377
|
+
if (topEntries.some((e) => e.name === ".git")) {
|
|
1378
|
+
return { ok: false, error: "looks_like_worktree", message: "directory contains a .git entry; refuse to delete" };
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
// Walk the tree: count files + check each file size. Bound by maxFiles.
|
|
1382
|
+
// We do this recursively so a sneaky `subdir/big.bin` is also caught.
|
|
1383
|
+
let fileCount = 0;
|
|
1384
|
+
const stack: string[] = [absTarget];
|
|
1385
|
+
while (stack.length > 0) {
|
|
1386
|
+
const dir = stack.pop()!;
|
|
1387
|
+
let entries: fs.Dirent[];
|
|
1388
|
+
try {
|
|
1389
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1390
|
+
} catch {
|
|
1391
|
+
return { ok: false, error: "fs_failed", message: `failed to read ${dir}` };
|
|
1392
|
+
}
|
|
1393
|
+
for (const e of entries) {
|
|
1394
|
+
const full = path.join(dir, e.name);
|
|
1395
|
+
if (e.isDirectory()) {
|
|
1396
|
+
stack.push(full);
|
|
1397
|
+
continue;
|
|
1398
|
+
}
|
|
1399
|
+
fileCount += 1;
|
|
1400
|
+
if (fileCount > maxFiles) {
|
|
1401
|
+
return { ok: false, error: "too_many_files", message: `directory contains more than ${maxFiles} files` };
|
|
1402
|
+
}
|
|
1403
|
+
try {
|
|
1404
|
+
const fileStat = fs.statSync(full);
|
|
1405
|
+
if (fileStat.size > maxFileSize) {
|
|
1406
|
+
return { ok: false, error: "file_too_large", message: `file exceeds ${maxFileSize} bytes: ${full}` };
|
|
1407
|
+
}
|
|
1408
|
+
} catch {
|
|
1409
|
+
return { ok: false, error: "fs_failed", message: `failed to stat ${full}` };
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// All checks pass. Delete.
|
|
1415
|
+
try {
|
|
1416
|
+
fs.rmSync(absTarget, { recursive: true, force: true });
|
|
1417
|
+
} catch (err: any) {
|
|
1418
|
+
return { ok: false, error: "fs_failed", message: `rm failed: ${err?.message ?? String(err)}` };
|
|
1419
|
+
}
|
|
1420
|
+
return { ok: true };
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
// ── Pull request helpers (change: add-worktree-from-pull-request) ──────────
|
|
1424
|
+
|
|
1425
|
+
import type { PullRequestInfo } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
|
|
1426
|
+
|
|
1427
|
+
export type ListPrCode = "gh_not_authed" | "no_remote" | "git_failed";
|
|
1428
|
+
|
|
1429
|
+
export interface ListPrSuccess {
|
|
1430
|
+
ok: true;
|
|
1431
|
+
data: PullRequestInfo[];
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
export interface ListPrFailure {
|
|
1435
|
+
ok: false;
|
|
1436
|
+
code: ListPrCode;
|
|
1437
|
+
stderr?: string;
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
/**
|
|
1441
|
+
* Collapse GitHub's `statusCheckRollup` array into a single summary.
|
|
1442
|
+
* Each entry has a `status` and/or `conclusion`; we derive a rollup:
|
|
1443
|
+
* - any failing → "failing"
|
|
1444
|
+
* - any pending → "pending"
|
|
1445
|
+
* - all success → "passing"
|
|
1446
|
+
* - empty / null → "none"
|
|
1447
|
+
*/
|
|
1448
|
+
function collapseCheckRollup(
|
|
1449
|
+
rollup: Array<{ status?: string; conclusion?: string }> | null | undefined,
|
|
1450
|
+
): PullRequestInfo["checkRollup"] {
|
|
1451
|
+
if (!rollup || rollup.length === 0) return "none";
|
|
1452
|
+
let hasPending = false;
|
|
1453
|
+
for (const check of rollup) {
|
|
1454
|
+
const conclusion = check.conclusion?.toUpperCase();
|
|
1455
|
+
const status = check.status?.toUpperCase();
|
|
1456
|
+
if (
|
|
1457
|
+
conclusion === "FAILURE" ||
|
|
1458
|
+
conclusion === "TIMED_OUT" ||
|
|
1459
|
+
conclusion === "CANCELLED" ||
|
|
1460
|
+
conclusion === "ACTION_REQUIRED" ||
|
|
1461
|
+
conclusion === "STARTUP_FAILURE" ||
|
|
1462
|
+
status === "FAILURE" ||
|
|
1463
|
+
status === "ERROR"
|
|
1464
|
+
) {
|
|
1465
|
+
return "failing";
|
|
1466
|
+
}
|
|
1467
|
+
if (
|
|
1468
|
+
status === "PENDING" ||
|
|
1469
|
+
status === "QUEUED" ||
|
|
1470
|
+
status === "IN_PROGRESS" ||
|
|
1471
|
+
status === "WAITING" ||
|
|
1472
|
+
status === "REQUESTED" ||
|
|
1473
|
+
conclusion === "" ||
|
|
1474
|
+
conclusion === undefined ||
|
|
1475
|
+
conclusion === null
|
|
1476
|
+
) {
|
|
1477
|
+
hasPending = true;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
return hasPending ? "pending" : "passing";
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
/**
|
|
1484
|
+
* List open pull requests for the repo at `cwd` via `gh pr list`.
|
|
1485
|
+
* Returns typed `PullRequestInfo[]` with a collapsed `checkRollup`.
|
|
1486
|
+
*/
|
|
1487
|
+
export function listPullRequests(opts: {
|
|
1488
|
+
cwd: string;
|
|
1489
|
+
ghPath: string;
|
|
1490
|
+
}): ListPrSuccess | ListPrFailure {
|
|
1491
|
+
const { cwd, ghPath } = opts;
|
|
1492
|
+
const args = [
|
|
1493
|
+
ghPath,
|
|
1494
|
+
"pr", "list",
|
|
1495
|
+
"--json", "number,title,headRefName,headRefOid,author,isDraft,isCrossRepository,statusCheckRollup",
|
|
1496
|
+
"--limit", "100",
|
|
1497
|
+
];
|
|
1498
|
+
let stdout: string;
|
|
1499
|
+
try {
|
|
1500
|
+
stdout = execSync(args.map(shellEscape).join(" "), {
|
|
1501
|
+
cwd,
|
|
1502
|
+
encoding: "utf-8",
|
|
1503
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1504
|
+
timeout: GIT_TIMEOUT,
|
|
1505
|
+
env: { ...process.env, GH_PROMPT_DISABLED: "1" },
|
|
1506
|
+
});
|
|
1507
|
+
} catch (err: any) {
|
|
1508
|
+
const stderr = [err?.stderr, err?.stdout, err?.message]
|
|
1509
|
+
.map((v) => (v == null ? "" : String(v)))
|
|
1510
|
+
.filter((s) => s.length > 0)
|
|
1511
|
+
.join("\n");
|
|
1512
|
+
const s = stderr.toLowerCase();
|
|
1513
|
+
if (
|
|
1514
|
+
/not logged in|authentication required|gh auth login|http 401/i.test(s)
|
|
1515
|
+
) {
|
|
1516
|
+
return { ok: false, code: "gh_not_authed", stderr };
|
|
1517
|
+
}
|
|
1518
|
+
if (
|
|
1519
|
+
/no such remote|does not appear to be a git repository|could not determine repo/i.test(s)
|
|
1520
|
+
) {
|
|
1521
|
+
return { ok: false, code: "no_remote", stderr };
|
|
1522
|
+
}
|
|
1523
|
+
return { ok: false, code: "git_failed", stderr };
|
|
1524
|
+
}
|
|
1525
|
+
let raw: any[];
|
|
1526
|
+
try {
|
|
1527
|
+
const parsed = JSON.parse(stdout);
|
|
1528
|
+
if (!Array.isArray(parsed)) {
|
|
1529
|
+
return { ok: false, code: "git_failed", stderr: "gh returned non-array JSON" };
|
|
1530
|
+
}
|
|
1531
|
+
raw = parsed;
|
|
1532
|
+
} catch {
|
|
1533
|
+
return { ok: false, code: "git_failed", stderr: "malformed JSON from gh" };
|
|
1534
|
+
}
|
|
1535
|
+
const data: PullRequestInfo[] = raw.map((pr: any) => ({
|
|
1536
|
+
number: pr.number,
|
|
1537
|
+
title: pr.title ?? "",
|
|
1538
|
+
headRefName: pr.headRefName ?? "",
|
|
1539
|
+
headRefOid: pr.headRefOid ?? "",
|
|
1540
|
+
author: pr.author?.login ?? "",
|
|
1541
|
+
isDraft: pr.isDraft === true,
|
|
1542
|
+
isCrossRepository: pr.isCrossRepository === true,
|
|
1543
|
+
checkRollup: collapseCheckRollup(pr.statusCheckRollup),
|
|
1544
|
+
}));
|
|
1545
|
+
return { ok: true, data };
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
// ── Create worktree from PR (change: add-worktree-from-pull-request) ──────
|
|
1549
|
+
|
|
1550
|
+
export type AddWorktreeFromPrError =
|
|
1551
|
+
| AddWorktreeError
|
|
1552
|
+
| "pr_not_found"
|
|
1553
|
+
| "gh_not_authed";
|
|
1554
|
+
|
|
1555
|
+
export interface AddWorktreeFromPrSuccess {
|
|
1556
|
+
ok: true;
|
|
1557
|
+
path: string;
|
|
1558
|
+
branch: string;
|
|
1559
|
+
prNumber: number;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
export interface AddWorktreeFromPrFailure {
|
|
1563
|
+
ok: false;
|
|
1564
|
+
error: AddWorktreeFromPrError;
|
|
1565
|
+
message: string;
|
|
1566
|
+
stderr?: string;
|
|
1567
|
+
orphanLikely?: boolean;
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
/**
|
|
1571
|
+
* Create a new worktree checked out at a pull request's head commit.
|
|
1572
|
+
*
|
|
1573
|
+
* Mechanic (Candidate B from design.md):
|
|
1574
|
+
* 1. `git fetch origin refs/pull/<N>/head:refs/pr/<N>`
|
|
1575
|
+
* 2. `git worktree add <path> -b pr-<N> refs/pr/<N>`
|
|
1576
|
+
*
|
|
1577
|
+
* Works for both same-repo and fork PRs because GitHub serves
|
|
1578
|
+
* `refs/pull/<N>/head` from the base repo.
|
|
1579
|
+
*/
|
|
1580
|
+
export function addWorktreeFromPr(opts: {
|
|
1581
|
+
cwd: string;
|
|
1582
|
+
prNumber: number;
|
|
1583
|
+
path?: string;
|
|
1584
|
+
}): AddWorktreeFromPrSuccess | AddWorktreeFromPrFailure {
|
|
1585
|
+
const { cwd, prNumber } = opts;
|
|
1586
|
+
if (!isGitRepo(cwd)) {
|
|
1587
|
+
return { ok: false, error: "not_a_repo", message: "not a git repository" };
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// Resolve repo root (same as addWorktree).
|
|
1591
|
+
const commonDirRaw = tryRun("git rev-parse --git-common-dir", cwd);
|
|
1592
|
+
if (!commonDirRaw) {
|
|
1593
|
+
return { ok: false, error: "not_a_repo", message: "unable to resolve git common-dir" };
|
|
1594
|
+
}
|
|
1595
|
+
const commonDirAbs = path.isAbsolute(commonDirRaw)
|
|
1596
|
+
? commonDirRaw
|
|
1597
|
+
: path.resolve(cwd, commonDirRaw);
|
|
1598
|
+
const repoRoot = path.dirname(commonDirAbs);
|
|
1599
|
+
|
|
1600
|
+
const localRef = `refs/pr/${prNumber}`;
|
|
1601
|
+
const localBranch = `pr-${prNumber}`;
|
|
1602
|
+
const worktreePath = opts.path ?? path.join(repoRoot, ".worktrees", `pr-${prNumber}`);
|
|
1603
|
+
|
|
1604
|
+
// Step 1: Fetch the PR head ref.
|
|
1605
|
+
const fetchCmd = [
|
|
1606
|
+
"git", "fetch", "origin",
|
|
1607
|
+
`refs/pull/${prNumber}/head:${localRef}`,
|
|
1608
|
+
].map(shellEscape).join(" ");
|
|
1609
|
+
try {
|
|
1610
|
+
execSync(fetchCmd, {
|
|
1611
|
+
cwd,
|
|
1612
|
+
encoding: "utf-8",
|
|
1613
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1614
|
+
timeout: GIT_TIMEOUT,
|
|
1615
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
|
|
1616
|
+
});
|
|
1617
|
+
} catch (err: any) {
|
|
1618
|
+
const stderr = String(err?.stderr ?? err?.message ?? "");
|
|
1619
|
+
if (/couldn.t find remote ref|no such ref/i.test(stderr)) {
|
|
1620
|
+
return { ok: false, error: "pr_not_found", message: `PR #${prNumber} not found`, stderr };
|
|
1621
|
+
}
|
|
1622
|
+
if (/authentication|permission denied|terminal prompts disabled/i.test(stderr)) {
|
|
1623
|
+
return { ok: false, error: "gh_not_authed", message: "git fetch auth failed", stderr };
|
|
1624
|
+
}
|
|
1625
|
+
return { ok: false, error: "git_failed", message: "git fetch failed", stderr };
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
// Step 2: Pre-flight path check.
|
|
1629
|
+
if (fs.existsSync(worktreePath)) {
|
|
1630
|
+
const isEmpty = (() => {
|
|
1631
|
+
try { return fs.readdirSync(worktreePath).length === 0; } catch { return false; }
|
|
1632
|
+
})();
|
|
1633
|
+
if (!isEmpty) {
|
|
1634
|
+
const orphanLikely = computeOrphanLikely(cwd, worktreePath);
|
|
1635
|
+
return {
|
|
1636
|
+
ok: false,
|
|
1637
|
+
error: "path_exists",
|
|
1638
|
+
message: `target path already exists and is not empty: ${worktreePath}`,
|
|
1639
|
+
orphanLikely,
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
// Step 3: Create the worktree.
|
|
1645
|
+
const addArgs = ["git", "worktree", "add", "-b", localBranch, worktreePath, localRef];
|
|
1646
|
+
try {
|
|
1647
|
+
execSync(addArgs.map(shellEscape).join(" "), {
|
|
1648
|
+
cwd,
|
|
1649
|
+
encoding: "utf-8",
|
|
1650
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1651
|
+
timeout: GIT_TIMEOUT,
|
|
1652
|
+
});
|
|
1653
|
+
} catch (err: any) {
|
|
1654
|
+
const stderr = String(err?.stderr ?? err?.message ?? "");
|
|
1655
|
+
if (/already used by worktree at|is already checked out at/i.test(stderr)) {
|
|
1656
|
+
return { ok: false, error: "branch_in_use", message: `branch pr-${prNumber} is already checked out in another worktree`, stderr };
|
|
1657
|
+
}
|
|
1658
|
+
if (/A branch named.*already exists|branch '.*' already exists/i.test(stderr)) {
|
|
1659
|
+
return { ok: false, error: "branch_exists", message: `branch "${localBranch}" already exists`, stderr };
|
|
1660
|
+
}
|
|
1661
|
+
if (/'.*' already exists/i.test(stderr)) {
|
|
1662
|
+
const orphanLikely = computeOrphanLikely(cwd, worktreePath);
|
|
1663
|
+
return { ok: false, error: "path_exists", message: `target path already exists: ${worktreePath}`, stderr, orphanLikely };
|
|
1664
|
+
}
|
|
1665
|
+
return { ok: false, error: "git_failed", message: "git worktree add failed", stderr };
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
// Housekeeping: append .worktrees/ to .git/info/exclude (same as addWorktree).
|
|
1669
|
+
if (!opts.path) {
|
|
1670
|
+
const excludePath = path.join(commonDirAbs, "info", "exclude");
|
|
1671
|
+
try {
|
|
1672
|
+
const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, "utf-8") : "";
|
|
1673
|
+
const result = ensureWorktreeExcludeLine(existing);
|
|
1674
|
+
if (result.appended) {
|
|
1675
|
+
fs.mkdirSync(path.dirname(excludePath), { recursive: true });
|
|
1676
|
+
fs.writeFileSync(excludePath, result.content);
|
|
1677
|
+
}
|
|
1678
|
+
} catch {
|
|
1679
|
+
// Non-fatal.
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
// Rewrite .pi/settings.json for the new worktree.
|
|
1684
|
+
rewriteWorktreePiSettings(worktreePath, repoRoot);
|
|
1685
|
+
|
|
1686
|
+
return { ok: true, path: worktreePath, branch: localBranch, prNumber };
|
|
1687
|
+
}
|