@uniqbit/mate-core 0.18.5 → 0.21.0
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/claude-capability-plugins/companion-mentions/.claude-plugin/marketplace.json +14 -0
- package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +8 -0
- package/claude-capability-plugins/companion-mentions/hooks/companion.ts +457 -0
- package/claude-capability-plugins/companion-mentions/hooks/hooks.json +1 -0
- package/claude-capability-plugins/companion-mentions/hooks/register.ts +403 -0
- package/claude-plugin/hooks/companion-instructions.mjs +9 -0
- package/claude-plugin/hooks/hooks.json +50 -2
- package/claude-plugin/hooks/rtk-worktree-git.mjs +58 -0
- package/claude-plugin/hooks/session-attention.mjs +10 -0
- package/claude-plugin/hooks/session-end.mjs +9 -0
- package/claude-plugin/hooks/session-guidance.mjs +1 -1
- package/claude-plugin/hooks/tokensave-route.mjs +52 -0
- package/opencode-plugin/src/server.ts +25 -3
- package/opencode-plugin/src/tui.tsx +3 -1
- package/opencode-plugin/tui.tsx +4 -1
- package/package.json +53 -15
- package/src/brand/art.generated.ts +69 -0
- package/src/brand/index.ts +12 -0
- package/src/brand/palette.ts +19 -0
- package/src/brand/svg.generated.ts +8 -0
- package/src/brand/terminal.ts +88 -0
- package/src/brand/types.ts +33 -0
- package/src/cli/commands/artifact/apply-context.ts +275 -0
- package/src/cli/commands/artifact/artifact.ts +12 -0
- package/src/cli/commands/artifact/delivery/archive.ts +125 -0
- package/src/cli/commands/artifact/delivery/branch-flags.ts +55 -0
- package/src/cli/commands/artifact/delivery/environment.ts +147 -0
- package/src/cli/commands/artifact/delivery/link.ts +210 -0
- package/src/cli/commands/artifact/delivery/output.ts +104 -0
- package/src/cli/commands/artifact/finish/command.ts +83 -8
- package/src/cli/commands/artifact/finish/engine.ts +91 -14
- package/src/cli/commands/artifact/finish/finisher.ts +10 -0
- package/src/cli/commands/artifact/finish/git.ts +132 -19
- package/src/cli/commands/artifact/finish/openspec.ts +180 -138
- package/src/cli/commands/artifact/finish/secret-scan.ts +43 -0
- package/src/cli/commands/artifact/finish/worktree-cleanup.ts +92 -0
- package/src/cli/commands/artifact/pending/command.ts +31 -3
- package/src/cli/commands/artifact/pending/discovery.ts +21 -57
- package/src/cli/commands/cap/graphify.ts +52 -3
- package/src/cli/commands/cap/index-cmd.ts +71 -15
- package/src/cli/commands/cap/openspec.ts +13 -25
- package/src/cli/commands/cap/tokensave.ts +7 -5
- package/src/cli/commands/companion/companion.ts +1 -1
- package/src/cli/commands/companion/link.ts +50 -5
- package/src/cli/commands/companion/open.ts +101 -51
- package/src/cli/commands/companion/sync.ts +10 -0
- package/src/cli/commands/companion/tui.ts +17 -7
- package/src/cli/commands/companion/update.ts +144 -66
- package/src/cli/commands/doctor.ts +317 -7
- package/src/cli/commands/factory/factory.ts +311 -0
- package/src/cli/commands/install.ts +180 -45
- package/src/cli/commands/launch/claude.ts +2 -0
- package/src/cli/commands/launch/shared.ts +48 -16
- package/src/cli/commands/plugin/install.ts +36 -15
- package/src/cli/commands/plugin/plugin.ts +3 -2
- package/src/cli/commands/report/adapter.ts +11 -2
- package/src/cli/commands/report/contract.ts +21 -0
- package/src/cli/commands/report/highlight.ts +34 -4
- package/src/cli/commands/report/index.ts +186 -171
- package/src/cli/commands/report/markdown.ts +105 -0
- package/src/cli/commands/report/palette.ts +118 -0
- package/src/cli/commands/report/renderer.ts +456 -153
- package/src/cli/commands/report/types.ts +16 -0
- package/src/cli/commands/session/context.ts +102 -0
- package/src/cli/commands/session/prepare.ts +32 -4
- package/src/cli/commands/session/registry.ts +90 -0
- package/src/cli/commands/setup.ts +50 -24
- package/src/cli/commands/shared/companion-selection.ts +3 -1
- package/src/cli/commands/studio/access.ts +6 -14
- package/src/cli/commands/studio/areas.ts +112 -33
- package/src/cli/commands/studio/companion-add.ts +87 -0
- package/src/cli/commands/studio/companion-removal.ts +86 -0
- package/src/cli/commands/studio/factory-credential.ts +35 -0
- package/src/cli/commands/studio/factory-git-tokens.ts +40 -0
- package/src/cli/commands/studio/factory-relay.ts +18 -0
- package/src/cli/commands/studio/graph-model.ts +61 -0
- package/src/cli/commands/studio/graph.ts +336 -0
- package/src/cli/commands/studio/index.ts +33 -6
- package/src/cli/commands/studio/mate-inventory.ts +1 -1
- package/src/cli/commands/studio/openspec-cli.ts +10 -58
- package/src/cli/commands/studio/payload.ts +292 -20
- package/src/cli/commands/studio/repository-add.ts +116 -0
- package/src/cli/commands/studio/routes.ts +47 -6
- package/src/cli/commands/studio/selection.ts +170 -17
- package/src/cli/commands/studio/server.ts +552 -327
- package/src/cli/commands/studio/services.ts +120 -0
- package/src/cli/commands/studio/skill-files.ts +133 -0
- package/src/cli/commands/studio/studio-app.ts +67 -0
- package/src/cli/commands/studio/terminal-assets.ts +21 -33
- package/src/cli/commands/studio/terminal.ts +128 -16
- package/src/cli/commands/studio/vault.ts +218 -44
- package/src/cli/commands/studio/views/model.ts +13 -0
- package/src/cli/commands/studio/views/vault/markdown-tree.ts +599 -0
- package/src/cli/commands/studio/views/vault/view.ts +185 -0
- package/src/cli/commands/studio/workset-session.ts +164 -0
- package/src/cli/commands/unwrap.ts +19 -0
- package/src/cli/commands/update.ts +55 -9
- package/src/cli/commands/vscode/release-vsix.json +4 -0
- package/src/cli/commands/vscode/setup.ts +213 -0
- package/src/cli/commands/vscode/vsix.ts +114 -0
- package/src/cli/commands/working/cleanup.ts +83 -18
- package/src/cli/commands/working/link.ts +76 -0
- package/src/cli/commands/working/working.ts +10 -0
- package/src/cli/commands/working/worktree.ts +547 -0
- package/src/cli/commands/wrap.ts +38 -20
- package/src/cli/companion-link-wizard.tsx +2 -0
- package/src/cli/companion-selector.tsx +2 -0
- package/src/cli/confirm.ts +2 -0
- package/src/cli/install-plan.tsx +127 -160
- package/src/cli/launch-selector.tsx +2 -0
- package/src/cli/main.ts +48 -5
- package/src/cli/parse-flags.ts +32 -6
- package/src/cli/repo-list-table.tsx +2 -0
- package/src/cli/setup-selector.tsx +86 -151
- package/src/cli/usage.ts +20 -1
- package/src/create-mate.ts +5 -4
- package/src/hooks/companion-instructions.ts +198 -0
- package/src/hooks/hook-io.ts +78 -0
- package/src/hooks/rtk-worktree-git.ts +48 -0
- package/src/hooks/session-banner.ts +24 -30
- package/src/hooks/session-end.ts +10 -0
- package/src/hooks/session-guidance.ts +18 -22
- package/src/hooks/session-prepare.ts +137 -34
- package/src/hooks/session-register.ts +199 -0
- package/src/hooks/tokensave-route.ts +30 -0
- package/src/hooks/validate-artifact-path.ts +121 -25
- package/src/index.ts +4 -0
- package/src/lib/apply-context/fingerprint.ts +174 -0
- package/src/lib/apply-context/protocol.ts +193 -0
- package/src/lib/change-layout.ts +154 -0
- package/src/lib/components/confirm-prompt.tsx +21 -9
- package/src/lib/components/select-menu.tsx +10 -3
- package/src/lib/components/spinner.tsx +4 -2
- package/src/lib/components/startup-progress.tsx +227 -41
- package/src/lib/components/text-input-display.tsx +2 -0
- package/src/lib/components/wizard-footer.tsx +2 -0
- package/src/lib/components/wizard-header.tsx +16 -12
- package/src/lib/context-mode-package.ts +24 -11
- package/src/lib/delivery/archive-change.ts +165 -0
- package/src/lib/delivery/branch-template.ts +122 -0
- package/src/lib/delivery/branches.ts +152 -0
- package/src/lib/delivery/checkout.ts +102 -0
- package/src/lib/delivery/environment.ts +37 -0
- package/src/lib/delivery/forge.ts +279 -0
- package/src/lib/delivery/merge-git.ts +273 -0
- package/src/lib/delivery/overlap.ts +209 -0
- package/src/lib/delivery/record-delivery.ts +392 -0
- package/src/lib/delivery/record.ts +417 -0
- package/src/lib/delivery/refresh.ts +288 -0
- package/src/lib/delivery/repository-access.ts +141 -0
- package/src/lib/delivery/resolve-branch.ts +430 -0
- package/src/lib/delivery/stages.ts +111 -0
- package/src/lib/delivery/token.ts +24 -0
- package/src/lib/factory/attach-client.ts +123 -0
- package/src/lib/factory/attach.ts +178 -0
- package/src/lib/factory/broker.ts +187 -0
- package/src/lib/factory/bun-commands.ts +39 -0
- package/src/lib/factory/client.ts +113 -0
- package/src/lib/factory/clone-url.ts +39 -0
- package/src/lib/factory/command.ts +77 -0
- package/src/lib/factory/credential-store.ts +153 -0
- package/src/lib/factory/frames.ts +77 -0
- package/src/lib/factory/git-auth.ts +61 -0
- package/src/lib/factory/git-credential-store.ts +181 -0
- package/src/lib/factory/ids.ts +68 -0
- package/src/lib/factory/keyed-serial.ts +27 -0
- package/src/lib/factory/outcomes/actions.ts +130 -0
- package/src/lib/factory/outcomes/index.ts +457 -0
- package/src/lib/factory/outcomes/lifecycle.ts +212 -0
- package/src/lib/factory/outcomes/runs.ts +81 -0
- package/src/lib/factory/outcomes/sessions.ts +60 -0
- package/src/lib/factory/prepare.ts +55 -0
- package/src/lib/factory/pty.ts +103 -0
- package/src/lib/factory/runner/companion-context.ts +178 -0
- package/src/lib/factory/runner/control.ts +92 -0
- package/src/lib/factory/runner/harness-agent.ts +250 -0
- package/src/lib/factory/runner/live.ts +159 -0
- package/src/lib/factory/runner/questions.ts +22 -0
- package/src/lib/factory/runner/rank.ts +26 -0
- package/src/lib/factory/runner/run-policy.ts +12 -0
- package/src/lib/factory/runner/run.ts +199 -0
- package/src/lib/factory/runner/scheduler.ts +498 -0
- package/src/lib/factory/runner/state.ts +233 -0
- package/src/lib/factory/runner/workflow.ts +546 -0
- package/src/lib/factory/runtime.ts +1081 -0
- package/src/lib/factory/sandbox.ts +292 -0
- package/src/lib/factory/worktree-branch.ts +17 -0
- package/src/lib/frontmatter.ts +18 -0
- package/src/lib/install.ts +66 -14
- package/src/lib/live-progress.ts +36 -0
- package/src/lib/member-choices.ts +67 -0
- package/src/lib/opencode-plugin-package.ts +5 -5
- package/src/lib/opencode-server.ts +238 -0
- package/src/lib/openspec-cli.ts +116 -0
- package/src/lib/openspec-scopes.ts +86 -0
- package/src/lib/orchestrator/adapters/base.ts +55 -22
- package/src/lib/orchestrator/adapters/claude-args.ts +50 -0
- package/src/lib/orchestrator/adapters/claude.ts +201 -43
- package/src/lib/orchestrator/adapters/opencode.ts +55 -2
- package/src/lib/orchestrator/checkout-adoption.ts +125 -0
- package/src/lib/orchestrator/companion-hub.ts +6 -1
- package/src/lib/orchestrator/companion-registry-store.ts +6 -2
- package/src/lib/orchestrator/config-store.ts +3 -2
- package/src/lib/orchestrator/editor.ts +32 -26
- package/src/lib/orchestrator/engine-floor.ts +48 -0
- package/src/lib/orchestrator/framework-context.ts +26 -14
- package/src/lib/orchestrator/global-config-store.ts +11 -0
- package/src/lib/orchestrator/launcher.ts +49 -3
- package/src/lib/orchestrator/openspec-store.ts +14 -54
- package/src/lib/orchestrator/projection-claude-commands.ts +36 -0
- package/src/lib/orchestrator/projection-claude-entry.ts +42 -21
- package/src/lib/orchestrator/projection-claude-links.ts +230 -0
- package/src/lib/orchestrator/projection-claude-skills.ts +39 -131
- package/src/lib/orchestrator/projection-companion-link.ts +12 -1
- package/src/lib/orchestrator/projection-entries.ts +121 -51
- package/src/lib/orchestrator/projection-opencode-copies.ts +93 -32
- package/src/lib/orchestrator/projection-openspec-store.ts +54 -9
- package/src/lib/orchestrator/projection-runtime-documents.ts +81 -49
- package/src/lib/orchestrator/projection-types.ts +63 -1
- package/src/lib/orchestrator/refresh-working-claude-links.ts +89 -0
- package/src/lib/orchestrator/registry-checkouts.ts +177 -0
- package/src/lib/orchestrator/repository-link.ts +216 -57
- package/src/lib/orchestrator/serving-claude-wrap.ts +43 -0
- package/src/lib/orchestrator/session-context-link.ts +73 -0
- package/src/lib/orchestrator/session-prepare.ts +87 -12
- package/src/lib/orchestrator/setup-compatibilities.ts +56 -70
- package/src/lib/orchestrator/types.ts +16 -2
- package/src/lib/orchestrator/umbrella-checkouts.ts +102 -0
- package/src/lib/orchestrator/working-repo-projection.ts +73 -10
- package/src/lib/orchestrator/workspace-document.ts +105 -0
- package/src/lib/orchestrator/workspace-inventory.ts +5 -1
- package/src/lib/orchestrator/wrap-pass.ts +23 -1
- package/src/lib/package-paths.ts +37 -0
- package/src/lib/public-npm.ts +105 -43
- package/src/lib/runtime-directory-refresh.ts +17 -1
- package/src/lib/session-attribution.ts +52 -0
- package/src/lib/session-state.ts +355 -0
- package/src/lib/session-stop.ts +64 -0
- package/src/lib/update-checker.ts +7 -1
- package/src/lib/usage/aggregate.ts +202 -0
- package/src/lib/usage/cache.ts +87 -0
- package/src/lib/usage/claude-pricing.ts +71 -0
- package/src/lib/usage/claude.ts +189 -0
- package/src/lib/usage/collect.ts +56 -0
- package/src/lib/usage/opencode.ts +188 -0
- package/src/lib/usage/records.ts +80 -0
- package/src/lib/usage/rtk-database.ts +72 -0
- package/src/lib/usage/savings.ts +209 -0
- package/src/lib/usage/scope.ts +182 -0
- package/src/lib/usage/source.ts +102 -0
- package/src/lib/usage/types.ts +143 -0
- package/src/lib/usage/window.ts +37 -0
- package/src/lib/workset/factory-local.ts +157 -0
- package/src/lib/workset/record.ts +547 -0
- package/src/lib/workset/repositories.ts +148 -0
- package/src/lib/workset/stage.ts +148 -0
- package/src/lib/workset/stages.ts +113 -0
- package/src/lib/workset/worktree-include.ts +161 -0
- package/src/lib/workset/worktree-index.ts +120 -0
- package/src/lib/workset/worktree.ts +1388 -0
- package/src/opencode/background-server.ts +145 -0
- package/src/opencode/companion-hooks.ts +151 -9
- package/src/opencode/companion-policy.ts +54 -22
- package/src/opencode/enter-worktree.ts +320 -0
- package/src/opencode/projected-guidance.ts +6 -2
- package/src/opencode/session-prepare.ts +2 -1
- package/src/opencode/session-register.ts +176 -0
- package/src/opencode/tui.tsx +24 -27
- package/src/plugins.ts +1 -0
- package/src/runtime/artifact-refusal.ts +63 -0
- package/src/runtime/claude-bg-isolation.ts +138 -0
- package/src/runtime/claude-delivery-plan.ts +121 -11
- package/src/runtime/commit-attribution-guard.ts +181 -0
- package/src/runtime/companion-git.ts +62 -12
- package/src/runtime/companion-guidance.ts +37 -12
- package/src/runtime/companion-instructions.ts +340 -0
- package/src/runtime/companion-lock.ts +30 -7
- package/src/runtime/current-branch.ts +24 -0
- package/src/runtime/entered-worktree.ts +24 -0
- package/src/runtime/env.ts +59 -8
- package/src/runtime/error-message.ts +4 -0
- package/src/runtime/git-layout.ts +366 -0
- package/src/runtime/git-tracked.ts +60 -0
- package/src/runtime/index.ts +29 -0
- package/src/runtime/launch-env-guard.ts +65 -0
- package/src/runtime/managed-block.ts +117 -0
- package/src/runtime/markdown-scan.ts +266 -0
- package/src/runtime/opencode-server-record.ts +136 -0
- package/src/runtime/physical-path.ts +111 -0
- package/src/runtime/policy.ts +50 -2
- package/src/runtime/projected-flag.ts +7 -0
- package/src/runtime/projected-guidance.ts +1 -0
- package/src/runtime/projection.ts +40 -6
- package/src/runtime/repo-destination.ts +72 -0
- package/src/runtime/repo-local.ts +29 -2
- package/src/runtime/rtk-git-guard.ts +66 -0
- package/src/runtime/runtime-directory.ts +5 -0
- package/src/runtime/runtime-document-manifest.ts +290 -29
- package/src/runtime/runtime-document-manifest.typecheck.ts +10 -0
- package/src/runtime/secret-guard.ts +169 -0
- package/src/runtime/secret-patterns.ts +397 -0
- package/src/runtime/secret-policy-weakening.ts +122 -0
- package/src/runtime/secret-scan.ts +90 -0
- package/src/runtime/serving-claude-wrap.ts +41 -0
- package/src/runtime/session-context.ts +99 -0
- package/src/runtime/session-kind.ts +13 -0
- package/src/runtime/session-registry.ts +434 -0
- package/src/runtime/shell-heredoc.ts +81 -0
- package/src/runtime/tokensave-route.ts +157 -0
- package/src/runtime/umbrella-folder.ts +56 -0
- package/src/runtime/wrap-state.ts +80 -15
- package/src/runtime/write-atomic.ts +64 -0
- package/src/studio.ts +163 -0
- package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +14 -10
- package/src/templates/capabilities/openspec-cap/mate-minimal/templates/spec.md +3 -5
- package/src/templates/capabilities/openspec-cap/mate-v1/schema.yaml +18 -102
- package/src/templates/capabilities/openspec-cap/mate-v1/templates/spec.md +3 -5
- package/src/templates/capabilities/openspec-cap/openspec-conventions.yaml +20 -14
- package/src/templates/mate-skills/THIRD-PARTY-NOTICES.md +40 -0
- package/src/templates/mate-skills/agents/mate-apply-change/SKILL.md +217 -0
- package/src/templates/mate-skills/agents/mate-apply-change/references/mate-compact-apply.md +47 -0
- package/src/templates/mate-skills/agents/mate-apply-change/references/openspec-apply-change.md +200 -0
- package/src/templates/mate-skills/agents/mate-archive-change/SKILL.md +81 -0
- package/src/templates/mate-skills/agents/{mate-openspec-backfill → mate-backfill-spec}/SKILL.md +11 -4
- package/src/templates/mate-skills/agents/mate-clarify-intent/SKILL.md +110 -0
- package/src/templates/mate-skills/agents/mate-explore-change/SKILL.md +70 -0
- package/src/templates/mate-skills/agents/mate-explore-change/references/openspec-explore.md +350 -0
- package/src/templates/mate-skills/agents/mate-grill-me/SKILL.md +11 -4
- package/src/templates/mate-skills/agents/mate-grill-with-docs/SKILL.md +2 -2
- package/src/templates/mate-skills/agents/mate-interview-me/SKILL.md +12 -5
- package/src/templates/mate-skills/agents/mate-propose-change/SKILL.md +106 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/mate-revise.md +45 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-propose.md +169 -0
- package/src/templates/mate-skills/agents/mate-propose-change/references/openspec-update-change.md +103 -0
- package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +271 -0
- package/src/templates/mate-skills/{claude/mate-artifact-publish → agents/mate-publish-artifact}/references/openspec.md +8 -5
- package/src/templates/mate-skills/agents/mate-show-me/SKILL.md +105 -20
- package/src/templates/mate-skills/agents/mate-simplify-code/SKILL.md +91 -68
- package/src/templates/mate-skills/claude/mate-apply-change/SKILL.md +217 -0
- package/src/templates/mate-skills/claude/mate-apply-change/references/mate-compact-apply.md +47 -0
- package/src/templates/mate-skills/claude/mate-apply-change/references/openspec-apply-change.md +200 -0
- package/src/templates/mate-skills/claude/mate-archive-change/SKILL.md +81 -0
- package/src/templates/mate-skills/claude/{mate-openspec-backfill → mate-backfill-spec}/SKILL.md +11 -4
- package/src/templates/mate-skills/claude/mate-clarify-intent/SKILL.md +110 -0
- package/src/templates/mate-skills/claude/mate-explore-change/SKILL.md +70 -0
- package/src/templates/mate-skills/claude/mate-explore-change/references/openspec-explore.md +350 -0
- package/src/templates/mate-skills/claude/mate-grill-me/SKILL.md +11 -4
- package/src/templates/mate-skills/claude/mate-grill-with-docs/SKILL.md +2 -2
- package/src/templates/mate-skills/claude/mate-interview-me/SKILL.md +12 -5
- package/src/templates/mate-skills/claude/mate-propose-change/SKILL.md +106 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/mate-revise.md +45 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-propose.md +169 -0
- package/src/templates/mate-skills/claude/mate-propose-change/references/openspec-update-change.md +103 -0
- package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +271 -0
- package/src/templates/mate-skills/{agents/mate-artifact-publish → claude/mate-publish-artifact}/references/openspec.md +8 -5
- package/src/templates/mate-skills/claude/mate-show-me/SKILL.md +105 -20
- package/src/templates/mate-skills/claude/mate-simplify-code/SKILL.md +91 -68
- package/src/templates/mate-skills/openspec-references.ts +142 -0
- package/src/templates/root/TEMPLATE_AGENTS.md +2 -2
- package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +4581 -397
- package/src/tools/setup/capabilities/companion-mentions.ts +27 -0
- package/src/tools/setup/capabilities/context-mode.ts +56 -7
- package/src/tools/setup/capabilities/graphify-gate.ts +31 -0
- package/src/tools/setup/capabilities/graphify-secrets.ts +243 -0
- package/src/tools/setup/capabilities/graphify.ts +46 -7
- package/src/tools/setup/capabilities/openspec.ts +163 -272
- package/src/tools/setup/capabilities/react-doctor.ts +8 -1
- package/src/tools/setup/capabilities/rtk.ts +97 -1
- package/src/tools/setup/capabilities/tokensave.ts +113 -71
- package/src/tools/setup/context-services.ts +9 -17
- package/src/tools/setup/dynamic-plugins/audiences.ts +65 -21
- package/src/tools/setup/dynamic-plugins/frozen.ts +32 -13
- package/src/tools/setup/dynamic-plugins/hydrate.ts +8 -7
- package/src/tools/setup/dynamic-plugins/install.ts +46 -48
- package/src/tools/setup/dynamic-plugins/loader.ts +11 -7
- package/src/tools/setup/dynamic-plugins/paths.ts +30 -10
- package/src/tools/setup/dynamic-plugins/verify.ts +10 -7
- package/src/tools/setup/dynamic-plugins/workspaces.ts +153 -0
- package/src/tools/setup/engine.ts +100 -23
- package/src/tools/setup/install-contract.ts +8 -0
- package/src/tools/setup/managed-output.ts +51 -0
- package/src/tools/setup/mate-skill-copies.ts +51 -0
- package/src/tools/setup/mate.ts +88 -13
- package/src/tools/setup/package-managers/uv.ts +73 -11
- package/src/tools/setup/plugin.ts +40 -0
- package/src/tools/setup/plugins/gitignore.ts +15 -9
- package/src/tools/setup/plugins/guidance.ts +7 -4
- package/src/tools/setup/providers/agent-file-sections.ts +4 -2
- package/src/tools/setup/providers/claude-attribution.ts +65 -0
- package/src/tools/setup/providers/claude-plugin-folders.ts +625 -0
- package/src/tools/setup/providers/claude-plugin-hooks.ts +89 -19
- package/src/tools/setup/providers/claude-worktree-plugins.ts +122 -0
- package/src/tools/setup/providers/claude.ts +332 -8
- package/src/tools/setup/providers/opencode.ts +180 -1
- package/src/tools/setup/utils.ts +22 -6
- package/src/tools/setup/working-repo-cleanup.ts +30 -2
- package/src/tools/setup/working-repo-local-state.ts +252 -75
- package/src/tools/setup.ts +196 -28
- package/studio-dist/client/assets/app-D9cw6szy.css +2 -0
- package/studio-dist/client/assets/artifacts-WD2ZXYrx.js +1 -0
- package/studio-dist/client/assets/button-Br0O1sXw.js +1 -0
- package/studio-dist/client/assets/combobox-DA7RAUUZ.js +1 -0
- package/studio-dist/client/assets/companion-view-CrabvxS8.js +1 -0
- package/studio-dist/client/assets/dist-Dm7MtyHc.js +5 -0
- package/studio-dist/client/assets/factory-DGS0E16C.js +6 -0
- package/studio-dist/client/assets/fields-6aXBpFhJ.js +1 -0
- package/studio-dist/client/assets/getting-started-Clde4w6P.js +1 -0
- package/studio-dist/client/assets/getting-started-D6kgWwWZ.js +1 -0
- package/studio-dist/client/assets/getting-started._topic-BiunccbT.js +1 -0
- package/studio-dist/client/assets/getting-started.index-DpiNoGw8.js +1 -0
- package/studio-dist/client/assets/graph-B_TCBVbu.js +2 -0
- package/studio-dist/client/assets/graph-canvas-Ba37Y5AE.js +3242 -0
- package/studio-dist/client/assets/guides-Du_RtJxP.js +1 -0
- package/studio-dist/client/assets/index-Df8L1LQa.js +40 -0
- package/studio-dist/client/assets/jsx-runtime-MZURdZre.js +1 -0
- package/studio-dist/client/assets/markdown-view-BOX6x0rL.js +1 -0
- package/studio-dist/client/assets/panel-dbmCx7Mx.js +1 -0
- package/studio-dist/client/assets/preload-helper-BLdHbfdN.js +1 -0
- package/studio-dist/client/assets/queries-RvHeXY12.js +1 -0
- package/studio-dist/client/assets/react-3QStrcDO.js +27 -0
- package/studio-dist/client/assets/report-url-XRL0x1SY.js +1 -0
- package/studio-dist/client/assets/reports-r3IK7Doz.js +1 -0
- package/studio-dist/client/assets/routes-C0A5LTFc.js +1 -0
- package/studio-dist/client/assets/select-CnaMd617.js +1 -0
- package/studio-dist/client/assets/skills-CzjzHpBT.js +1 -0
- package/studio-dist/client/assets/specs-B0ldF_6J.js +1 -0
- package/studio-dist/client/assets/specs-view-BnCLA0gW.js +1 -0
- package/studio-dist/client/assets/spinner-Dcm3fqK1.js +1 -0
- package/studio-dist/client/assets/steps-C0p2N1Pb.js +1 -0
- package/studio-dist/client/assets/store-Dw34catY.js +1 -0
- package/studio-dist/client/assets/studio-Cpz_HRHp.js +100 -0
- package/studio-dist/client/assets/studio-queries-ibmpFo6R.js +2 -0
- package/studio-dist/client/assets/terminal-eU5fzQzv.css +1 -0
- package/studio-dist/client/assets/usage-C2QJ_0IZ.js +55 -0
- package/studio-dist/client/assets/useAnchoredPopupScrollLock-Bj-FWb8z.js +1 -0
- package/studio-dist/client/assets/useMutation-aAr2uiay.js +1 -0
- package/studio-dist/client/assets/useSelector-AYcH7lB0.js +2 -0
- package/studio-dist/client/assets/vault-BGcxkSIY.js +1 -0
- package/studio-dist/client/assets/warnings-R1cE1rLf.js +1 -0
- package/studio-dist/client/assets/wasm-inline-C2en61B5.js +1 -0
- package/studio-dist/client/assets/workflow-C2qTrMDH.js +1 -0
- package/studio-dist/server/assets/__23tanstack-start-server-fn-resolver-Bn896ZYj.js +122 -0
- package/studio-dist/server/assets/_tanstack-start-manifest_v.js +162 -0
- package/studio-dist/server/assets/actions-D8erOphH.js +44 -0
- package/studio-dist/server/assets/actions-DYSv-9VV.js +60 -0
- package/studio-dist/server/assets/artifacts-DnF9L3dZ.js +216 -0
- package/studio-dist/server/assets/button-CgOIVdmD.js +10240 -0
- package/studio-dist/server/assets/combobox-DV_s9W0s.js +483 -0
- package/studio-dist/server/assets/companion-view-BKVXD3TO.js +39 -0
- package/studio-dist/server/assets/companions-C7fctnU9.js +31 -0
- package/studio-dist/server/assets/createServerRpc-bFKFpGFG.js +11 -0
- package/studio-dist/server/assets/dist-DpJWKyCm.js +5582 -0
- package/studio-dist/server/assets/empty-plugin-adapters-Cipd4ZH4.js +4 -0
- package/studio-dist/server/assets/factory-C7Ybg0xG.js +3075 -0
- package/studio-dist/server/assets/factory-Df5uAHjb.js +116 -0
- package/studio-dist/server/assets/fields-BbieQTD0.js +1190 -0
- package/studio-dist/server/assets/getting-started-B136TP57.js +4 -0
- package/studio-dist/server/assets/getting-started-CRxMWorQ.js +67 -0
- package/studio-dist/server/assets/getting-started._topic-DJKQAzYl.js +13 -0
- package/studio-dist/server/assets/getting-started.index-D84gec1t.js +13 -0
- package/studio-dist/server/assets/graph-CSje3029.js +801 -0
- package/studio-dist/server/assets/graph-DDZzXM1L.js +16 -0
- package/studio-dist/server/assets/graph-canvas-22bWB5-2.js +21066 -0
- package/studio-dist/server/assets/graph-wire-BdSUx0G5.js +58 -0
- package/studio-dist/server/assets/guides-D9dk1Frq.js +13 -0
- package/studio-dist/server/assets/guides-IE-19POz.js +5 -0
- package/studio-dist/server/assets/guides.server-vcYRY5wx.js +66 -0
- package/studio-dist/server/assets/jsx-runtime-Bt0s0YKS.js +451 -0
- package/studio-dist/server/assets/markdown-view-BR8dJ7aR.js +105 -0
- package/studio-dist/server/assets/model-PyPALjii.js +18 -0
- package/studio-dist/server/assets/panel-BR_t9iMM.js +169 -0
- package/studio-dist/server/assets/queries-DWoTin-q.js +32 -0
- package/studio-dist/server/assets/react-CdqSUhaL.js +89 -0
- package/studio-dist/server/assets/redirect-BaZ_QyqF.js +39 -0
- package/studio-dist/server/assets/report-url-BUXPcE_8.js +9 -0
- package/studio-dist/server/assets/reports-CQ9qQ1-n.js +141 -0
- package/studio-dist/server/assets/reports-dYDEoBeq.js +18 -0
- package/studio-dist/server/assets/router-DkRHNTpE.js +11638 -0
- package/studio-dist/server/assets/routes-B6GfOew4.js +473 -0
- package/studio-dist/server/assets/search-BJnWLfkG.js +55 -0
- package/studio-dist/server/assets/select-Af7Wibii.js +1609 -0
- package/studio-dist/server/assets/shell-Hq-hXgnT.js +53 -0
- package/studio-dist/server/assets/skills-B7nEuVbx.js +267 -0
- package/studio-dist/server/assets/skills-B_YYL7q8.js +28 -0
- package/studio-dist/server/assets/specs-BpLUFntA.js +51 -0
- package/studio-dist/server/assets/specs-view-0peMVd22.js +426 -0
- package/studio-dist/server/assets/spinner-CdwJW4VB.js +20 -0
- package/studio-dist/server/assets/start-h3ICWwd2.js +36 -0
- package/studio-dist/server/assets/steps-D56DApvK.js +181 -0
- package/studio-dist/server/assets/store-Cs17okNG.js +280 -0
- package/studio-dist/server/assets/studio-CAcKp3bM.js +10340 -0
- package/studio-dist/server/assets/studio-queries-BtRGzDdh.js +1451 -0
- package/studio-dist/server/assets/usage-COdjd1gD.js +25570 -0
- package/studio-dist/server/assets/usage-f6pqE1tm.js +24 -0
- package/studio-dist/server/assets/useAnchoredPopupScrollLock-DlBKHRw7.js +756 -0
- package/studio-dist/server/assets/useMutation-DzTZGenE.js +690 -0
- package/studio-dist/server/assets/useSelector-DUmCUXAs.js +3387 -0
- package/studio-dist/server/assets/utils-C9CX1kcy.js +221 -0
- package/studio-dist/server/assets/vault-BDuIUq0F.js +1035 -0
- package/studio-dist/server/assets/vault-BVLp6zu3.js +85 -0
- package/studio-dist/server/assets/views-flRUr21z.js +80 -0
- package/studio-dist/server/assets/warnings-CDy9pdgL.js +24 -0
- package/studio-dist/server/assets/wasm-inline-CNeBKGwC.js +3 -0
- package/studio-dist/server/assets/workflow-D9GKI2EV.js +680 -0
- package/studio-dist/server/server.js +16640 -0
- package/wrappers/bin/graphify +52 -4
- package/wrappers/bin/openspec +33 -9
- package/wrappers/lib/graphify-gate.mjs +8 -0
- package/src/cli/commands/report/collector.ts +0 -288
- package/src/cli/commands/studio/views/client.ts +0 -654
- package/src/cli/commands/studio/views/companion-picker.tsx +0 -95
- package/src/cli/commands/studio/views/companion-selector.tsx +0 -94
- package/src/cli/commands/studio/views/dashboard/changes.tsx +0 -107
- package/src/cli/commands/studio/views/dashboard/index.tsx +0 -19
- package/src/cli/commands/studio/views/document.tsx +0 -842
- package/src/cli/commands/studio/views/error.tsx +0 -20
- package/src/cli/commands/studio/views/reports/index.tsx +0 -49
- package/src/cli/commands/studio/views/selection-fields.tsx +0 -14
- package/src/cli/commands/studio/views/skills/index.tsx +0 -87
- package/src/cli/commands/studio/views/specs/index.tsx +0 -157
- package/src/cli/commands/studio/views/styles.ts +0 -519
- package/src/cli/commands/studio/views/terminal.tsx +0 -484
- package/src/cli/commands/studio/views/vault/state.ts +0 -43
- package/src/cli/commands/studio/views/warnings.tsx +0 -21
- package/src/cli/commands/studio/views/workflow/index.tsx +0 -21
- package/src/cli/commands/studio/views/workflow/steps.ts +0 -337
- package/src/cli/commands/studio/views/workflow/transcript.tsx +0 -190
- package/src/lib/components/theme.ts +0 -2
- package/src/templates/mate-skills/agents/mate-artifact-publish/SKILL.md +0 -185
- package/src/templates/mate-skills/claude/mate-artifact-publish/SKILL.md +0 -185
- package/src/tools/setup/git-utils.ts +0 -30
- package/src/tools/setup/runtime-documents.ts +0 -291
|
@@ -0,0 +1,1388 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import { FRAMEWORK_NAME } from "../../framework";
|
|
6
|
+
import { gitEnvironment, withoutAskPass } from "../../runtime/companion-git";
|
|
7
|
+
import { withCompanionLock } from "../../runtime/companion-lock";
|
|
8
|
+
import { errorMessage } from "../../runtime/error-message";
|
|
9
|
+
import { readGitLayout } from "../../runtime/git-layout";
|
|
10
|
+
import { repoLocalRegistryPath } from "../../runtime/repo-local";
|
|
11
|
+
import type { WrapRuntime } from "../../runtime/runtime-document-manifest";
|
|
12
|
+
import { readWrapState, WRAP_RUNTIMES } from "../../runtime/wrap-state";
|
|
13
|
+
import { cleanupWorkingRepository } from "../../tools/setup/working-repo-cleanup";
|
|
14
|
+
import { locateChange } from "../change-layout";
|
|
15
|
+
import { classifyBranch, configuredProtectedPatterns } from "../delivery/branches";
|
|
16
|
+
import { deliveryCheckout } from "../delivery/checkout";
|
|
17
|
+
import { type DeliveryRecord, readDeliveryRecord } from "../delivery/record";
|
|
18
|
+
import {
|
|
19
|
+
newBranchBase,
|
|
20
|
+
resolveDeliveryBranch,
|
|
21
|
+
worktreeAddArgs,
|
|
22
|
+
type BranchSource,
|
|
23
|
+
} from "../delivery/resolve-branch";
|
|
24
|
+
import { repositoryPath } from "../delivery/forge";
|
|
25
|
+
import { scopedRepositories } from "../openspec-scopes";
|
|
26
|
+
import { attendedLockOptions } from "../orchestrator/companion-git-sync";
|
|
27
|
+
import { readCompanionConfig } from "../orchestrator/config-store";
|
|
28
|
+
import {
|
|
29
|
+
findRepoLocalLinkTo,
|
|
30
|
+
readCompanionRegistry,
|
|
31
|
+
writeRepoLocalRegistryEntry,
|
|
32
|
+
} from "../orchestrator/repository-link";
|
|
33
|
+
import { projectionEntries } from "../orchestrator/projection-entries";
|
|
34
|
+
import type { LinkedRepository } from "../orchestrator/types";
|
|
35
|
+
import { linkedCheckoutsOf, type EntryCheckout } from "../orchestrator/umbrella-checkouts";
|
|
36
|
+
import { runWrapPass } from "../orchestrator/wrap-pass";
|
|
37
|
+
import {
|
|
38
|
+
indexWorktree,
|
|
39
|
+
UMBRELLA_NOT_INDEXED,
|
|
40
|
+
type IndexOutcome,
|
|
41
|
+
type TokensaveRunner,
|
|
42
|
+
} from "./worktree-index";
|
|
43
|
+
import { copyIncludedFiles, selectIncludedFiles, type IncludeOutcome } from "./worktree-include";
|
|
44
|
+
import { findWorkset, readWorksets, resolveWorksetBranch, resolveWorksetOf } from "./record";
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Workset worktrees outside the factory: one Git worktree per Working Repository at
|
|
48
|
+
* `<main checkout>.worktrees/<workset-id>`, on the Workset's Delivery Branch, linked to
|
|
49
|
+
* the companion, wrapped like its main checkout and installed. Ignored files named by the
|
|
50
|
+
* main checkout's include files are copied in; other env files are reported by path only.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
export interface GitResult {
|
|
54
|
+
code: number;
|
|
55
|
+
stdout: string;
|
|
56
|
+
stderr: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface GitRunOptions {
|
|
60
|
+
/** Added to the promptless environment every command gets. */
|
|
61
|
+
env?: Record<string, string>;
|
|
62
|
+
timeoutMs?: number;
|
|
63
|
+
/** Written to standard input, which is then closed. */
|
|
64
|
+
input?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type GitRunner = (
|
|
68
|
+
cwd: string,
|
|
69
|
+
args: string[],
|
|
70
|
+
options?: GitRunOptions,
|
|
71
|
+
) => Promise<GitResult>;
|
|
72
|
+
|
|
73
|
+
/** Runs an install command; `stream` passes its output through, otherwise it is discarded. */
|
|
74
|
+
export type InstallRunner = (cwd: string, command: string[], stream: boolean) => Promise<boolean>;
|
|
75
|
+
|
|
76
|
+
/** Wraps the worktree for `runtimes`; resolves to the failure message, or null. */
|
|
77
|
+
export type WorktreeWrapper = (
|
|
78
|
+
companionPath: string,
|
|
79
|
+
repository: LinkedRepository,
|
|
80
|
+
runtimes: readonly WrapRuntime[],
|
|
81
|
+
) => Promise<string | null>;
|
|
82
|
+
|
|
83
|
+
export interface WorktreeDeps {
|
|
84
|
+
git?: GitRunner;
|
|
85
|
+
install?: InstallRunner;
|
|
86
|
+
writeLink?: typeof writeRepoLocalRegistryEntry;
|
|
87
|
+
readWrapState?: typeof readWrapState;
|
|
88
|
+
wrap?: WorktreeWrapper;
|
|
89
|
+
unwrap?: typeof cleanupWorkingRepository;
|
|
90
|
+
tokensave?: TokensaveRunner;
|
|
91
|
+
/** The process's working directory; a worktree holding it is kept. */
|
|
92
|
+
cwd?: () => string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export type InstallOutcome = "ok" | "failed" | "skipped";
|
|
96
|
+
|
|
97
|
+
export interface WrapOutcome {
|
|
98
|
+
/** The runtimes the main checkout is wrapped for. */
|
|
99
|
+
runtimes: WrapRuntime[];
|
|
100
|
+
outcome: InstallOutcome;
|
|
101
|
+
reason?: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface WorktreeRepositoryResult {
|
|
105
|
+
repository: string;
|
|
106
|
+
/** The main checkout the worktree belongs to. */
|
|
107
|
+
checkout: string;
|
|
108
|
+
path: string;
|
|
109
|
+
branch: string;
|
|
110
|
+
action: "created" | "reused";
|
|
111
|
+
install: { command: string | null; outcome: InstallOutcome; reason?: string };
|
|
112
|
+
wrap: WrapOutcome;
|
|
113
|
+
/** The worktree's tokensave index; a failure only warns. */
|
|
114
|
+
index: IndexOutcome;
|
|
115
|
+
/** Ignored files copied from the main checkout by its include files. */
|
|
116
|
+
include: IncludeOutcome;
|
|
117
|
+
/** Env files of the main checkout the worktree lacks, relative to the repository root. */
|
|
118
|
+
missingEnv: string[];
|
|
119
|
+
/** Set when a step for this repository failed. */
|
|
120
|
+
error?: string;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** An Umbrella Repository's mirrored worktree, linked and wrapped like the umbrella. */
|
|
124
|
+
export interface UmbrellaWorktreeResult {
|
|
125
|
+
/** The Umbrella Repository. */
|
|
126
|
+
path: string;
|
|
127
|
+
/** The mirrored worktree folder holding the children's worktrees. */
|
|
128
|
+
worktree: string;
|
|
129
|
+
action: "created" | "reused";
|
|
130
|
+
/** The children whose worktree the folder holds, as `org/repository`. */
|
|
131
|
+
repositories: string[];
|
|
132
|
+
wrap: WrapOutcome;
|
|
133
|
+
/** The folder's tokensave index, kept when the umbrella has one; a failure only warns. */
|
|
134
|
+
index: IndexOutcome;
|
|
135
|
+
/** Set when linking or wrapping the folder failed; its worktrees stay. */
|
|
136
|
+
error?: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface WorktreeResult {
|
|
140
|
+
workset: string;
|
|
141
|
+
ok: boolean;
|
|
142
|
+
repositories: WorktreeRepositoryResult[];
|
|
143
|
+
/** Present only when a repository is an Umbrella Repository's child. */
|
|
144
|
+
umbrella?: UmbrellaWorktreeResult;
|
|
145
|
+
diagnostics: string[];
|
|
146
|
+
warnings: string[];
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface PruneEntry {
|
|
150
|
+
workset: string;
|
|
151
|
+
repository: string;
|
|
152
|
+
path: string;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** A Workset to prune: its id and the changes whose Delivery Records name its branches. */
|
|
156
|
+
export interface PruneTarget {
|
|
157
|
+
id: string;
|
|
158
|
+
changes: readonly string[];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** An Umbrella Repository's mirrored worktree of a Workset. */
|
|
162
|
+
export interface PruneMirrorEntry {
|
|
163
|
+
workset: string;
|
|
164
|
+
umbrella: string;
|
|
165
|
+
path: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface PruneResult {
|
|
169
|
+
removed: PruneEntry[];
|
|
170
|
+
kept: (PruneEntry & { reason: string })[];
|
|
171
|
+
/** Present only when a pruned Workset has a mirrored umbrella worktree. */
|
|
172
|
+
umbrellas?: {
|
|
173
|
+
removed: PruneMirrorEntry[];
|
|
174
|
+
kept: (PruneMirrorEntry & { reason: string })[];
|
|
175
|
+
};
|
|
176
|
+
warnings: string[];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Never prompts: worktree creation runs unattended, often under `--json`. */
|
|
180
|
+
function promptlessEnv(): NodeJS.ProcessEnv {
|
|
181
|
+
return {
|
|
182
|
+
...withoutAskPass(gitEnvironment()),
|
|
183
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
184
|
+
GCM_INTERACTIVE: "never",
|
|
185
|
+
} as NodeJS.ProcessEnv;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const runGit: GitRunner = (cwd, args, options = {}) =>
|
|
189
|
+
new Promise<GitResult>((resolve) => {
|
|
190
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
191
|
+
// Unbounded: a merge check pipes a whole `git log -p` range into `git patch-id`.
|
|
192
|
+
const child = execFile(
|
|
193
|
+
"git",
|
|
194
|
+
args,
|
|
195
|
+
{ cwd, env: { ...promptlessEnv(), ...options.env }, maxBuffer: Infinity },
|
|
196
|
+
(error, stdout, stderr) => {
|
|
197
|
+
clearTimeout(timer);
|
|
198
|
+
const code = error ? (typeof error.code === "number" ? error.code : 1) : 0;
|
|
199
|
+
resolve({ code, stdout: String(stdout), stderr: String(stderr) });
|
|
200
|
+
},
|
|
201
|
+
);
|
|
202
|
+
if (options.input !== undefined) {
|
|
203
|
+
child.stdin?.on("error", () => {});
|
|
204
|
+
child.stdin?.end(options.input);
|
|
205
|
+
}
|
|
206
|
+
const { timeoutMs } = options;
|
|
207
|
+
if (timeoutMs !== undefined) {
|
|
208
|
+
// Resolved without awaiting `close`: an SSH grandchild may hold the pipes open.
|
|
209
|
+
timer = setTimeout(() => {
|
|
210
|
+
child.kill("SIGKILL");
|
|
211
|
+
resolve({ code: 1, stdout: "", stderr: `git ${args[0]} timed out after ${timeoutMs} ms` });
|
|
212
|
+
}, timeoutMs);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
const FETCH_TIMEOUT_MS = 60_000;
|
|
217
|
+
|
|
218
|
+
/** `git fetch --prune origin`, bounded; SSH runs in batch mode unless the user set their own command. */
|
|
219
|
+
async function fetchOrigin(git: GitRunner, checkout: string): Promise<GitResult> {
|
|
220
|
+
const ownSsh =
|
|
221
|
+
Boolean(process.env.GIT_SSH_COMMAND || process.env.GIT_SSH) ||
|
|
222
|
+
(await git(checkout, ["config", "--get", "core.sshCommand"])).code === 0;
|
|
223
|
+
return git(checkout, ["fetch", "--prune", "origin"], {
|
|
224
|
+
env: ownSsh ? {} : { GIT_SSH_COMMAND: "ssh -o BatchMode=yes" },
|
|
225
|
+
timeoutMs: FETCH_TIMEOUT_MS,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Serialized with `mate wrap`, Session Prepare and every sync, which rewrite the same manifests. */
|
|
230
|
+
const runWrap: WorktreeWrapper = async (companionPath, repository, runtimes) => {
|
|
231
|
+
const locked = await withCompanionLock(companionPath, attendedLockOptions(companionPath), () =>
|
|
232
|
+
runWrapPass(companionPath, repository, { runtimes }),
|
|
233
|
+
);
|
|
234
|
+
if (!locked.acquired) return "another companion synchronization is still running";
|
|
235
|
+
return locked.value.kind === "failed" ? locked.value.message : null;
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const runInstall: InstallRunner = (cwd, [command, ...args], stream) =>
|
|
239
|
+
new Promise((resolve) => {
|
|
240
|
+
const child = spawn(command!, args, { cwd, stdio: stream ? "inherit" : "ignore" });
|
|
241
|
+
child.on("error", () => resolve(false));
|
|
242
|
+
child.on("close", (code) => resolve(code === 0));
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
/** First match wins, at the worktree root only: workspace managers install the whole repository. */
|
|
246
|
+
const LOCKFILES: [string, string[]][] = [
|
|
247
|
+
["bun.lock", ["bun", "install"]],
|
|
248
|
+
["bun.lockb", ["bun", "install"]],
|
|
249
|
+
["pnpm-lock.yaml", ["pnpm", "install"]],
|
|
250
|
+
["yarn.lock", ["yarn", "install"]],
|
|
251
|
+
["package-lock.json", ["npm", "ci"]],
|
|
252
|
+
];
|
|
253
|
+
|
|
254
|
+
/** The install skip reason of a repository whose worktree could not be created. */
|
|
255
|
+
export const NOT_CREATED = "worktree not created";
|
|
256
|
+
|
|
257
|
+
const ENV_NAME = /^\.env(\..+)?$/;
|
|
258
|
+
const ENV_EXAMPLE = /\.(example|sample|template|dist)$/;
|
|
259
|
+
|
|
260
|
+
async function exists(candidate: string): Promise<boolean> {
|
|
261
|
+
try {
|
|
262
|
+
await fs.access(candidate);
|
|
263
|
+
return true;
|
|
264
|
+
} catch {
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Real path when it exists; otherwise the nearest existing parent resolved, so macOS `/var` matches `/private/var`. */
|
|
270
|
+
async function canonical(candidate: string): Promise<string> {
|
|
271
|
+
try {
|
|
272
|
+
return await fs.realpath(candidate);
|
|
273
|
+
} catch {
|
|
274
|
+
const parent = path.dirname(candidate);
|
|
275
|
+
if (parent === candidate) return candidate;
|
|
276
|
+
return path.join(await canonical(parent), path.basename(candidate));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function worktreePathFor(mainCheckout: string, worksetId: string): string {
|
|
281
|
+
return path.join(
|
|
282
|
+
path.dirname(mainCheckout),
|
|
283
|
+
`${path.basename(mainCheckout)}.worktrees`,
|
|
284
|
+
worksetId,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
interface WorktreeEntry {
|
|
289
|
+
path: string;
|
|
290
|
+
/** Short branch name, or null when detached or bare. */
|
|
291
|
+
branch: string | null;
|
|
292
|
+
/** `git worktree lock` set; `git worktree remove` refuses it without `--force`. */
|
|
293
|
+
locked: boolean;
|
|
294
|
+
/** Set when Git marks the entry prunable (its directory or `.git` file is gone): Git's reason. */
|
|
295
|
+
stale: string | null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function listWorktrees(git: GitRunner, repo: string): Promise<WorktreeEntry[] | null> {
|
|
299
|
+
const result = await git(repo, ["worktree", "list", "--porcelain"]);
|
|
300
|
+
if (result.code !== 0) return null;
|
|
301
|
+
const entries = result.stdout.split(/\n\n+/).flatMap((block) => {
|
|
302
|
+
let entryPath: string | null = null;
|
|
303
|
+
let branch: string | null = null;
|
|
304
|
+
let locked = false;
|
|
305
|
+
let stale: string | null = null;
|
|
306
|
+
for (const line of block.split("\n")) {
|
|
307
|
+
if (line.startsWith("worktree ")) entryPath = line.slice("worktree ".length);
|
|
308
|
+
else if (line.startsWith("branch refs/heads/"))
|
|
309
|
+
branch = line.slice("branch refs/heads/".length);
|
|
310
|
+
else if (line === "locked" || line.startsWith("locked ")) locked = true;
|
|
311
|
+
else if (line === "prunable" || line.startsWith("prunable ")) {
|
|
312
|
+
stale = line.slice("prunable".length).trim() || "prunable";
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return entryPath ? [{ path: entryPath, branch, locked, stale }] : [];
|
|
316
|
+
});
|
|
317
|
+
return Promise.all(
|
|
318
|
+
entries.map(async (entry) => ({ ...entry, path: await canonical(entry.path) })),
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** A linked checkout; `umbrella` is set for an Umbrella Repository's child, whose id is the umbrella's. */
|
|
323
|
+
type LinkedCheckout = LinkedRepository & { umbrella?: string };
|
|
324
|
+
|
|
325
|
+
interface LinkedLookup {
|
|
326
|
+
linked: LinkedCheckout | null;
|
|
327
|
+
/** Registered paths that no longer exist. */
|
|
328
|
+
missing: string[];
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Every checkout linked to the companion, in lookup order, with its `org/repository`. */
|
|
332
|
+
interface LinkedIndex {
|
|
333
|
+
checkouts: { linked: LinkedCheckout; identity: string | null }[];
|
|
334
|
+
/** Registered paths that no longer exist. */
|
|
335
|
+
missing: string[];
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** The first checkout in the index whose `origin` is the repository. */
|
|
339
|
+
function linkedCheckout(index: LinkedIndex, repository: string): LinkedLookup {
|
|
340
|
+
// The first match in registry order decides, umbrella children in name order.
|
|
341
|
+
const match = index.checkouts.find(
|
|
342
|
+
({ identity }) => identity?.toLowerCase() === repository.toLowerCase(),
|
|
343
|
+
);
|
|
344
|
+
return { linked: match?.linked ?? null, missing: index.missing };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* The existing registered checkouts, an Umbrella Repository's children included, then
|
|
349
|
+
* the one the repo-local link holding `cwd` names, so an entry left naming a removed
|
|
350
|
+
* folder does not hide it. Read once per run: expanding an umbrella reads every child's
|
|
351
|
+
* `origin`.
|
|
352
|
+
*/
|
|
353
|
+
async function linkedIndex(
|
|
354
|
+
companionPath: string,
|
|
355
|
+
git: GitRunner,
|
|
356
|
+
cwd: string,
|
|
357
|
+
): Promise<LinkedIndex> {
|
|
358
|
+
let repos: LinkedRepository[] = [];
|
|
359
|
+
try {
|
|
360
|
+
repos = (await readCompanionRegistry(companionPath)).repos;
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
363
|
+
}
|
|
364
|
+
const present = await Promise.all(repos.map((repo) => exists(repo.path)));
|
|
365
|
+
const current = await findRepoLocalLinkTo(cwd, companionPath);
|
|
366
|
+
const entries = [...repos.filter((_, index) => present[index]), ...(current ? [current] : [])];
|
|
367
|
+
const readOrigin = async (checkout: string) => {
|
|
368
|
+
// Raw config, not `remote get-url`, so `insteadOf` rewrites do not change the identity.
|
|
369
|
+
const remote = await git(checkout, ["config", "--get", "remote.origin.url"]);
|
|
370
|
+
return remote.code === 0 ? remote.stdout.trim() || null : null;
|
|
371
|
+
};
|
|
372
|
+
const expanded = await Promise.all(
|
|
373
|
+
entries.map(async (entry) =>
|
|
374
|
+
Promise.all(
|
|
375
|
+
(await linkedCheckoutsOf(entry, readOrigin, readOrigin)).map(async (checkout) => ({
|
|
376
|
+
linked: { ...entry, ...(await mainChild(checkout)) },
|
|
377
|
+
identity: checkout.remote ? repositoryPath(checkout.remote) : null,
|
|
378
|
+
})),
|
|
379
|
+
),
|
|
380
|
+
),
|
|
381
|
+
);
|
|
382
|
+
return {
|
|
383
|
+
checkouts: expanded.flat(),
|
|
384
|
+
missing: repos.filter((_, at) => !present[at]).map((repo) => repo.path),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* The checkout and umbrella an entry's checkout stands for. A child of a mirrored worktree
|
|
390
|
+
* `<umbrella>.worktrees/<id>/<name>`, a worktree of `<umbrella>/<name>`, stands for that
|
|
391
|
+
* main checkout, so the real umbrella stays the one mirrored.
|
|
392
|
+
*/
|
|
393
|
+
async function mainChild(checkout: EntryCheckout): Promise<{ path: string; umbrella?: string }> {
|
|
394
|
+
const { path: child } = checkout;
|
|
395
|
+
if (!checkout.umbrella) return { path: child };
|
|
396
|
+
// Canonical, so an umbrella reached by a registry path and by Git's paths is one.
|
|
397
|
+
const umbrella = await canonical(checkout.umbrella);
|
|
398
|
+
const layout = readGitLayout(child);
|
|
399
|
+
if (layout?.kind === "linked" && path.basename(layout.commonDir) === ".git") {
|
|
400
|
+
const main = path.dirname(layout.commonDir);
|
|
401
|
+
const real = await canonical(path.dirname(main));
|
|
402
|
+
const mirrored =
|
|
403
|
+
path.basename(main) === path.basename(child) &&
|
|
404
|
+
(await canonical(worktreePathFor(real, path.basename(umbrella)))) === umbrella;
|
|
405
|
+
if (mirrored) return { path: main, umbrella: real };
|
|
406
|
+
}
|
|
407
|
+
return { path: child, umbrella };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
interface Plan {
|
|
411
|
+
repository: string;
|
|
412
|
+
/** The main checkout's Repository Link id, which the worktree's link repeats. */
|
|
413
|
+
repositoryId: string;
|
|
414
|
+
checkout: string;
|
|
415
|
+
target: string;
|
|
416
|
+
branch: string;
|
|
417
|
+
source: BranchSource;
|
|
418
|
+
/** Start point when `source` is `new`. */
|
|
419
|
+
base?: string;
|
|
420
|
+
reuse: boolean;
|
|
421
|
+
/** `--take-branch`: `branch` is checked out in `checkout`, which is detached first. */
|
|
422
|
+
take?: boolean;
|
|
423
|
+
/** Set for an Umbrella Repository's child: the umbrella, whose mirrored worktree holds `target`. */
|
|
424
|
+
umbrella?: string;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** A resolved Workset: its id and the repositories that get a worktree. */
|
|
428
|
+
interface Target {
|
|
429
|
+
id: string;
|
|
430
|
+
repositories: readonly string[];
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** The explicit record with this id, or the diagnostics naming it and every invalid record. */
|
|
434
|
+
async function recordTarget(companionPath: string, worksetId: string): Promise<Target | string[]> {
|
|
435
|
+
const { worksets, problems } = await readWorksets(companionPath);
|
|
436
|
+
const record = worksets.find((entry) => entry.id === worksetId);
|
|
437
|
+
if (record) return record;
|
|
438
|
+
return [
|
|
439
|
+
`no valid Workset ${worksetId}`,
|
|
440
|
+
...problems.map((problem) => `${problem.path}: ${problem.reason}`),
|
|
441
|
+
];
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* The change's Workset as `mate artifact link` resolves it: the record listing it, else the
|
|
446
|
+
* implicit single-change Workset with the repositories of the change's scopes.
|
|
447
|
+
*/
|
|
448
|
+
async function changeTarget(companionPath: string, change: string): Promise<Target | string[]> {
|
|
449
|
+
const location = await locateChange(companionPath, change);
|
|
450
|
+
if (!location || location.archived) return [`no active change ${change}`];
|
|
451
|
+
const resolution = await resolveWorksetOf(companionPath, change);
|
|
452
|
+
if (resolution.id === null) return resolution.diagnostics;
|
|
453
|
+
if (!resolution.implicit) {
|
|
454
|
+
const record = await findWorkset(companionPath, resolution.id);
|
|
455
|
+
return record ?? [`no valid Workset ${resolution.id}`];
|
|
456
|
+
}
|
|
457
|
+
const repositories = await scopedRepositories(location.dir);
|
|
458
|
+
if (repositories.length === 0) return [`change ${change} names no repository in its scopes`];
|
|
459
|
+
return { id: resolution.id, repositories };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
type ProtectedPatterns = readonly string[];
|
|
463
|
+
|
|
464
|
+
type PlanOptions = Pick<CreateWorktreesOptions, "ticket" | "takeBranch"> & {
|
|
465
|
+
/** The companion's protected patterns, read once for every repository's take. */
|
|
466
|
+
protectedPatterns?: ProtectedPatterns;
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
/** Phase 1: every check for every repository; any failure means nothing is created. */
|
|
470
|
+
async function planWorktrees(
|
|
471
|
+
companionPath: string,
|
|
472
|
+
target: Target,
|
|
473
|
+
git: GitRunner,
|
|
474
|
+
cwd: string,
|
|
475
|
+
options: Pick<CreateWorktreesOptions, "ticket" | "takeBranch">,
|
|
476
|
+
): Promise<{ plans: Plan[]; mirror?: Mirror; diagnostics: string[]; warnings: string[] }> {
|
|
477
|
+
const warnings: string[] = [];
|
|
478
|
+
const index = await linkedIndex(companionPath, git, cwd);
|
|
479
|
+
const planOptions: PlanOptions = options.takeBranch
|
|
480
|
+
? {
|
|
481
|
+
...options,
|
|
482
|
+
protectedPatterns: configuredProtectedPatterns(
|
|
483
|
+
(await readCompanionConfig(companionPath)).capabilities ?? [],
|
|
484
|
+
),
|
|
485
|
+
}
|
|
486
|
+
: options;
|
|
487
|
+
const checked = await Promise.all(
|
|
488
|
+
target.repositories.map((repository) =>
|
|
489
|
+
planRepository(companionPath, target.id, repository, git, index, warnings, planOptions),
|
|
490
|
+
),
|
|
491
|
+
);
|
|
492
|
+
const plans = checked.filter((entry): entry is Plan => !Array.isArray(entry));
|
|
493
|
+
const diagnostics = checked.flatMap((entry) => (Array.isArray(entry) ? entry : []));
|
|
494
|
+
const mirror = await planMirror(companionPath, target.id, plans);
|
|
495
|
+
if (Array.isArray(mirror)) return { plans, diagnostics: [...diagnostics, ...mirror], warnings };
|
|
496
|
+
return { plans, ...(mirror ? { mirror } : {}), diagnostics, warnings };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** The mirrored worktree a Workset's umbrella children get. */
|
|
500
|
+
interface Mirror {
|
|
501
|
+
umbrella: string;
|
|
502
|
+
/** The umbrella's Repository Link id, which the folder's link repeats. */
|
|
503
|
+
repositoryId: string;
|
|
504
|
+
folder: string;
|
|
505
|
+
/** The folder already is this umbrella's mirrored worktree. */
|
|
506
|
+
reuse: boolean;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* The mirrored worktree of the plans' Umbrella Repository, or the diagnostics that stop
|
|
511
|
+
* the run: the folder must be this umbrella's mirrored worktree, or hold nothing but OS
|
|
512
|
+
* metadata, Mate's material, and its children's reused worktrees, as a run interrupted
|
|
513
|
+
* before linking leaves it.
|
|
514
|
+
*/
|
|
515
|
+
async function planMirror(
|
|
516
|
+
companionPath: string,
|
|
517
|
+
worksetId: string,
|
|
518
|
+
plans: readonly Plan[],
|
|
519
|
+
): Promise<Mirror | string[] | undefined> {
|
|
520
|
+
const children = plans.filter((plan) => plan.umbrella);
|
|
521
|
+
const umbrellas = [...new Set(children.map((plan) => plan.umbrella!))];
|
|
522
|
+
if (umbrellas.length === 0) return undefined;
|
|
523
|
+
if (umbrellas.length > 1) {
|
|
524
|
+
return [
|
|
525
|
+
`the Workset spans the Umbrella Repositories ${umbrellas.join(", ")}; a mirrored worktree serves one`,
|
|
526
|
+
];
|
|
527
|
+
}
|
|
528
|
+
const umbrella = umbrellas[0]!;
|
|
529
|
+
const repositoryId = children[0]!.repositoryId;
|
|
530
|
+
const folder = await canonical(worktreePathFor(umbrella, worksetId));
|
|
531
|
+
if (await isMirrorOf(folder, companionPath, repositoryId)) {
|
|
532
|
+
return { umbrella, repositoryId, folder, reuse: true };
|
|
533
|
+
}
|
|
534
|
+
// A link of its own names another companion or id: someone else's folder.
|
|
535
|
+
if (await exists(repoLocalRegistryPath(folder))) {
|
|
536
|
+
return [`${folder} exists and is not the mirrored worktree of ${umbrella}`];
|
|
537
|
+
}
|
|
538
|
+
const listed = await fs.readdir(folder).catch(() => []);
|
|
539
|
+
const material = mirrorMaterial();
|
|
540
|
+
const reused = new Set(
|
|
541
|
+
children.filter((plan) => plan.reuse).map((plan) => path.basename(plan.target)),
|
|
542
|
+
);
|
|
543
|
+
const foreign = listed.filter((name) => !material.has(name) && !reused.has(name));
|
|
544
|
+
if (foreign.length === 0) return { umbrella, repositoryId, folder, reuse: false };
|
|
545
|
+
return [`${folder} exists and is not the mirrored worktree of ${umbrella}`];
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/** `folder` carries its own repo-local link to the companion under the umbrella's id. */
|
|
549
|
+
async function isMirrorOf(
|
|
550
|
+
folder: string,
|
|
551
|
+
companionPath: string,
|
|
552
|
+
repositoryId: string,
|
|
553
|
+
): Promise<boolean> {
|
|
554
|
+
const link = await findRepoLocalLinkTo(folder, companionPath);
|
|
555
|
+
return link !== null && link.id === repositoryId && (await canonical(link.path)) === folder;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** One repository's plan, or the diagnostics that stop the run. */
|
|
559
|
+
async function planRepository(
|
|
560
|
+
companionPath: string,
|
|
561
|
+
worksetId: string,
|
|
562
|
+
repository: string,
|
|
563
|
+
git: GitRunner,
|
|
564
|
+
index: LinkedIndex,
|
|
565
|
+
warnings: string[],
|
|
566
|
+
{ ticket, takeBranch, protectedPatterns }: PlanOptions,
|
|
567
|
+
): Promise<Plan | string[]> {
|
|
568
|
+
const { linked, missing } = linkedCheckout(index, repository);
|
|
569
|
+
if (!linked) {
|
|
570
|
+
// An identity problem outranks the missing link.
|
|
571
|
+
const identity = await resolveWorksetBranch(companionPath, worksetId, repository);
|
|
572
|
+
if (identity.id === null) return identity.diagnostics.map((line) => `${repository}: ${line}`);
|
|
573
|
+
const why = missing.map((entry) => `registered path ${entry} does not exist`).join("; ");
|
|
574
|
+
return [
|
|
575
|
+
`${repository}: not linked to ${companionPath} on this machine${why ? ` (${why})` : ""}`,
|
|
576
|
+
];
|
|
577
|
+
}
|
|
578
|
+
// Resolved after the fetch, so a branch pushed elsewhere counts as existing.
|
|
579
|
+
const fetched = await fetchOrigin(git, linked.path);
|
|
580
|
+
if (fetched.code !== 0) {
|
|
581
|
+
warnings.push(
|
|
582
|
+
`${repository}: fetching origin failed, using local refs: ${fetched.stderr.trim()}`,
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
// Every probe runs through the same runner; it already adds the promptless environment.
|
|
586
|
+
const checkout = deliveryCheckout(linked.path, (args, { input, timeoutMs }) =>
|
|
587
|
+
git(linked.path, [...args], {
|
|
588
|
+
env: { GIT_NO_LAZY_FETCH: "1" },
|
|
589
|
+
...(input !== undefined ? { input } : {}),
|
|
590
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
591
|
+
}),
|
|
592
|
+
);
|
|
593
|
+
const resolution = await resolveDeliveryBranch(
|
|
594
|
+
checkout,
|
|
595
|
+
{ companionPath, repository, worksetId },
|
|
596
|
+
ticket ? { ticket } : {},
|
|
597
|
+
);
|
|
598
|
+
// Concerns the companion, not a repository: reported once, first.
|
|
599
|
+
const { templateDiagnostic } = resolution;
|
|
600
|
+
if (templateDiagnostic && !warnings.includes(templateDiagnostic)) {
|
|
601
|
+
warnings.unshift(templateDiagnostic);
|
|
602
|
+
}
|
|
603
|
+
const { branch, source } = resolution;
|
|
604
|
+
if (branch === null || source === null) {
|
|
605
|
+
return resolution.diagnostics.map((line) => `${repository}: ${line}`);
|
|
606
|
+
}
|
|
607
|
+
// A resolved branch's diagnostics only inform, e.g. a ticket that names nothing.
|
|
608
|
+
warnings.push(...resolution.diagnostics.map((line) => `${repository}: ${line}`));
|
|
609
|
+
const entries = await listWorktrees(git, linked.path);
|
|
610
|
+
const main = entries?.[0];
|
|
611
|
+
if (!main) return [`${repository}: cannot list the worktrees of ${linked.path}`];
|
|
612
|
+
const target = await canonical(
|
|
613
|
+
linked.umbrella
|
|
614
|
+
? path.join(worktreePathFor(linked.umbrella, worksetId), path.basename(linked.path))
|
|
615
|
+
: worktreePathFor(main.path, worksetId),
|
|
616
|
+
);
|
|
617
|
+
const atTarget = entries.find((entry) => entry.path === target);
|
|
618
|
+
// A stale entry is never reused: wrapping it would only refill a folder without a checkout.
|
|
619
|
+
const stale = entries.find(
|
|
620
|
+
(entry) => entry.stale && (entry.path === target || entry.branch === branch),
|
|
621
|
+
);
|
|
622
|
+
if (stale) {
|
|
623
|
+
return [
|
|
624
|
+
`${repository}: ${stale.path} is a stale worktree entry (${stale.stale}); remove any folder left there, run \`git worktree prune\` in ${main.path}, then retry`,
|
|
625
|
+
];
|
|
626
|
+
}
|
|
627
|
+
const plan = {
|
|
628
|
+
repository,
|
|
629
|
+
repositoryId: linked.id,
|
|
630
|
+
checkout: main.path,
|
|
631
|
+
branch,
|
|
632
|
+
source,
|
|
633
|
+
...(linked.umbrella ? { umbrella: linked.umbrella } : {}),
|
|
634
|
+
};
|
|
635
|
+
const elsewhere = entries.find((entry) => entry.branch === branch && entry.path !== target);
|
|
636
|
+
const inherited = resolution.inheritedFrom.join(", ");
|
|
637
|
+
const take = Boolean(takeBranch && elsewhere?.path === main.path);
|
|
638
|
+
// An inherited branch is the dependency's worktree; one branch has one worktree.
|
|
639
|
+
// In the main checkout, only `--take-branch` moves it out.
|
|
640
|
+
if (elsewhere && inherited && !atTarget && !take) {
|
|
641
|
+
if (elsewhere.path === main.path) {
|
|
642
|
+
return [
|
|
643
|
+
`${repository}: ${branch}, inherited from ${inherited}, is checked out in ${main.path}; work there or switch it to another branch`,
|
|
644
|
+
];
|
|
645
|
+
}
|
|
646
|
+
warnings.push(
|
|
647
|
+
`${repository}: ${branch} is inherited from ${inherited}; reusing its worktree at ${elsewhere.path}`,
|
|
648
|
+
);
|
|
649
|
+
return { ...plan, target: elsewhere.path, reuse: true };
|
|
650
|
+
}
|
|
651
|
+
const reuse = atTarget?.branch === branch;
|
|
652
|
+
if (!reuse && (atTarget || (await exists(target)))) {
|
|
653
|
+
return [`${repository}: ${target} exists and is not a worktree of ${repository} on ${branch}`];
|
|
654
|
+
}
|
|
655
|
+
if (take) {
|
|
656
|
+
const refusal = await takeRefusal(git, main.path, branch, checkout, protectedPatterns ?? []);
|
|
657
|
+
if (refusal) return [`${repository}: ${refusal}`];
|
|
658
|
+
return { ...plan, target, reuse: false, take: true };
|
|
659
|
+
}
|
|
660
|
+
if (elsewhere) return [`${repository}: ${branch} is already checked out at ${elsewhere.path}`];
|
|
661
|
+
return {
|
|
662
|
+
...plan,
|
|
663
|
+
target,
|
|
664
|
+
base: source === "new" ? await newBranchBase(checkout.hasRef) : undefined,
|
|
665
|
+
reuse,
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** Why `--take-branch` leaves `branch` in the main checkout `main`, or null to take it. */
|
|
670
|
+
async function takeRefusal(
|
|
671
|
+
git: GitRunner,
|
|
672
|
+
main: string,
|
|
673
|
+
branch: string,
|
|
674
|
+
checkout: { defaultBranch(): Promise<string> },
|
|
675
|
+
patterns: ProtectedPatterns,
|
|
676
|
+
): Promise<string | null> {
|
|
677
|
+
const protection = classifyBranch(branch, {
|
|
678
|
+
defaultBranch: await checkout.defaultBranch(),
|
|
679
|
+
patterns,
|
|
680
|
+
});
|
|
681
|
+
if (protection.protected) {
|
|
682
|
+
return `--take-branch does not take the protected branch ${branch} out of ${main}`;
|
|
683
|
+
}
|
|
684
|
+
return trackedChangesRefusal(git, main);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** Why `main`'s tracked changes block a take, or null when it has none. */
|
|
688
|
+
async function trackedChangesRefusal(git: GitRunner, main: string): Promise<string | null> {
|
|
689
|
+
const status = await git(main, ["status", "--porcelain", "-z", "--untracked-files=no"]);
|
|
690
|
+
if (status.code !== 0) return `cannot read the status of ${main}: ${status.stderr.trim()}`;
|
|
691
|
+
// `XY path\0`; a rename or copy, in either column, adds its source as the next field,
|
|
692
|
+
// which is skipped.
|
|
693
|
+
const fields = status.stdout.split("\0");
|
|
694
|
+
const changed: string[] = [];
|
|
695
|
+
for (let at = 0; at < fields.length; at++) {
|
|
696
|
+
const field = fields[at]!;
|
|
697
|
+
if (field.length <= 3) continue;
|
|
698
|
+
changed.push(field.slice(3));
|
|
699
|
+
if (/[RC]/.test(field.slice(0, 2))) at++;
|
|
700
|
+
}
|
|
701
|
+
if (changed.length > 0) {
|
|
702
|
+
return `${main} has uncommitted changes to tracked files (${changed.join(", ")}); commit or stash them, then retry --take-branch`;
|
|
703
|
+
}
|
|
704
|
+
return null;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
async function addWorktree(git: GitRunner, plan: Plan): Promise<string | null> {
|
|
708
|
+
const result = await git(plan.checkout, worktreeAddArgs(plan, plan.target, plan.base));
|
|
709
|
+
return result.code === 0 ? null : `creating the worktree failed: ${result.stderr.trim()}`;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* `--take-branch`: detach the main checkout, add the worktree, and undo both on failure.
|
|
714
|
+
* Earlier repositories' takes stay: their worktrees are made, as for any later failure.
|
|
715
|
+
*/
|
|
716
|
+
async function takeIntoWorktree(
|
|
717
|
+
git: GitRunner,
|
|
718
|
+
plan: Plan,
|
|
719
|
+
warnings: string[],
|
|
720
|
+
): Promise<string | null> {
|
|
721
|
+
// Checked again: earlier repositories' setup may have given the developer time to edit.
|
|
722
|
+
const changed = await trackedChangesRefusal(git, plan.checkout);
|
|
723
|
+
if (changed) return changed;
|
|
724
|
+
const detached = await git(plan.checkout, ["switch", "--detach"]);
|
|
725
|
+
if (detached.code !== 0) return `detaching ${plan.checkout} failed: ${detached.stderr.trim()}`;
|
|
726
|
+
const failure = await addWorktree(git, plan);
|
|
727
|
+
if (!failure) {
|
|
728
|
+
warnings.push(
|
|
729
|
+
`${plan.repository}: ${plan.checkout} is now on a detached HEAD; ${plan.branch} moved to ${plan.target}`,
|
|
730
|
+
);
|
|
731
|
+
return null;
|
|
732
|
+
}
|
|
733
|
+
// Back to the state before the command, so a failed take changes nothing visible. A
|
|
734
|
+
// worktree registered before the add failed still holds the branch; the planned target
|
|
735
|
+
// did not exist, so removing it drops only what the add left. A failed remove matters
|
|
736
|
+
// only when the switch back fails too: an add that registered nothing leaves nothing.
|
|
737
|
+
const removed = await git(plan.checkout, ["worktree", "remove", "--force", plan.target]);
|
|
738
|
+
await git(plan.checkout, ["worktree", "prune"]);
|
|
739
|
+
const restored = await git(plan.checkout, ["switch", plan.branch]);
|
|
740
|
+
if (restored.code === 0) return failure;
|
|
741
|
+
const kept =
|
|
742
|
+
removed.code === 0 ? "" : `; removing ${plan.target} failed: ${removed.stderr.trim()}`;
|
|
743
|
+
return `${failure}${kept}; switching ${plan.checkout} back to ${plan.branch} failed: ${restored.stderr.trim()}`;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** The runtimes `checkout` is wrapped for, in wrap order. */
|
|
747
|
+
async function wrappedRuntimes(checkout: string, deps: WorktreeDeps): Promise<WrapRuntime[]> {
|
|
748
|
+
const state = await (deps.readWrapState ?? readWrapState)(checkout);
|
|
749
|
+
return WRAP_RUNTIMES.filter((runtime) => state.runtimes.has(runtime));
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** Wraps the worktree for exactly the runtimes its main checkout is wrapped for. */
|
|
753
|
+
async function wrapWorktree(
|
|
754
|
+
companionPath: string,
|
|
755
|
+
checkout: string,
|
|
756
|
+
repository: LinkedRepository,
|
|
757
|
+
deps: WorktreeDeps,
|
|
758
|
+
): Promise<WrapOutcome> {
|
|
759
|
+
let runtimes: WrapRuntime[];
|
|
760
|
+
try {
|
|
761
|
+
runtimes = await wrappedRuntimes(checkout, deps);
|
|
762
|
+
} catch (error) {
|
|
763
|
+
return {
|
|
764
|
+
runtimes: [],
|
|
765
|
+
outcome: "failed",
|
|
766
|
+
reason: `cannot read the wrap of ${checkout}: ${errorMessage(error)}`,
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
if (runtimes.length === 0) {
|
|
770
|
+
return { runtimes, outcome: "skipped", reason: "main checkout not wrapped" };
|
|
771
|
+
}
|
|
772
|
+
let failure: string | null;
|
|
773
|
+
try {
|
|
774
|
+
failure = await (deps.wrap ?? runWrap)(companionPath, repository, runtimes);
|
|
775
|
+
} catch (error) {
|
|
776
|
+
failure = errorMessage(error);
|
|
777
|
+
}
|
|
778
|
+
return failure ? { runtimes, outcome: "failed", reason: failure } : { runtimes, outcome: "ok" };
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
async function installCommand(worktree: string): Promise<string[] | null> {
|
|
782
|
+
for (const [lockfile, command] of LOCKFILES) {
|
|
783
|
+
// oxlint-disable-next-line no-await-in-loop -- lockfile order decides
|
|
784
|
+
if (await exists(path.join(worktree, lockfile))) return command;
|
|
785
|
+
}
|
|
786
|
+
return null;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** Ignored, untracked env files of the main checkout absent from the worktree; paths only. */
|
|
790
|
+
async function missingEnvFiles(
|
|
791
|
+
git: GitRunner,
|
|
792
|
+
checkout: string,
|
|
793
|
+
worktree: string,
|
|
794
|
+
): Promise<string[]> {
|
|
795
|
+
const listed = await git(checkout, [
|
|
796
|
+
"ls-files",
|
|
797
|
+
"-z",
|
|
798
|
+
"--others",
|
|
799
|
+
"--ignored",
|
|
800
|
+
"--exclude-standard",
|
|
801
|
+
"--directory",
|
|
802
|
+
]);
|
|
803
|
+
if (listed.code !== 0) return [];
|
|
804
|
+
const candidates = listed.stdout
|
|
805
|
+
.split("\0")
|
|
806
|
+
.filter(
|
|
807
|
+
(entry) =>
|
|
808
|
+
entry &&
|
|
809
|
+
!entry.endsWith("/") &&
|
|
810
|
+
!entry.split("/").includes("node_modules") &&
|
|
811
|
+
ENV_NAME.test(path.posix.basename(entry)) &&
|
|
812
|
+
!ENV_EXAMPLE.test(entry),
|
|
813
|
+
);
|
|
814
|
+
const missing = await Promise.all(
|
|
815
|
+
candidates.map(async (entry) => ((await exists(path.join(worktree, entry))) ? null : entry)),
|
|
816
|
+
);
|
|
817
|
+
return missing.filter((entry): entry is string => entry !== null).toSorted();
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
export interface CreateWorktreesOptions {
|
|
821
|
+
install: boolean;
|
|
822
|
+
/**
|
|
823
|
+
* Names a new Delivery Branch by the template (default `workset/<TICKET>-<id>`); an existing
|
|
824
|
+
* or recorded one wins.
|
|
825
|
+
*/
|
|
826
|
+
ticket?: string;
|
|
827
|
+
/** Pass the installer's output through; false discards it, as `--json` needs. */
|
|
828
|
+
streamInstall: boolean;
|
|
829
|
+
/**
|
|
830
|
+
* Take a resolved, unprotected branch, inherited ones included, out of a main checkout
|
|
831
|
+
* without tracked changes: detach that checkout, then add the worktree on the branch.
|
|
832
|
+
*/
|
|
833
|
+
takeBranch?: boolean;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Creates or reuses the Workset's worktree in each of its Working Repositories. Checks
|
|
838
|
+
* everything first and creates nothing when a check fails; a later failure is reported
|
|
839
|
+
* for its repository and keeps the worktrees already made.
|
|
840
|
+
*/
|
|
841
|
+
export async function createWorksetWorktrees(
|
|
842
|
+
companionPath: string,
|
|
843
|
+
worksetId: string,
|
|
844
|
+
options: CreateWorktreesOptions,
|
|
845
|
+
deps: WorktreeDeps = {},
|
|
846
|
+
): Promise<WorktreeResult> {
|
|
847
|
+
const target = await recordTarget(companionPath, worksetId);
|
|
848
|
+
return createTargetWorktrees(companionPath, worksetId, target, options, deps);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/**
|
|
852
|
+
* As `createWorksetWorktrees`, for the Workset the change resolves to, implicit ones
|
|
853
|
+
* included; writes no Workset record.
|
|
854
|
+
*/
|
|
855
|
+
export async function createChangeWorktrees(
|
|
856
|
+
companionPath: string,
|
|
857
|
+
change: string,
|
|
858
|
+
options: CreateWorktreesOptions,
|
|
859
|
+
deps: WorktreeDeps = {},
|
|
860
|
+
): Promise<WorktreeResult> {
|
|
861
|
+
const target = await changeTarget(companionPath, change);
|
|
862
|
+
return createTargetWorktrees(companionPath, change, target, options, deps);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/** `fallbackId` names the result when the target did not resolve. */
|
|
866
|
+
async function createTargetWorktrees(
|
|
867
|
+
companionPath: string,
|
|
868
|
+
fallbackId: string,
|
|
869
|
+
target: Target | string[],
|
|
870
|
+
options: CreateWorktreesOptions,
|
|
871
|
+
deps: WorktreeDeps,
|
|
872
|
+
): Promise<WorktreeResult> {
|
|
873
|
+
if (Array.isArray(target)) {
|
|
874
|
+
return { workset: fallbackId, ok: false, repositories: [], diagnostics: target, warnings: [] };
|
|
875
|
+
}
|
|
876
|
+
const worksetId = target.id;
|
|
877
|
+
const git = deps.git ?? runGit;
|
|
878
|
+
const cwd = (deps.cwd ?? process.cwd)();
|
|
879
|
+
const { plans, mirror, diagnostics, warnings } = await planWorktrees(
|
|
880
|
+
companionPath,
|
|
881
|
+
target,
|
|
882
|
+
git,
|
|
883
|
+
cwd,
|
|
884
|
+
options,
|
|
885
|
+
);
|
|
886
|
+
if (diagnostics.length > 0) {
|
|
887
|
+
return { workset: worksetId, ok: false, repositories: [], diagnostics, warnings };
|
|
888
|
+
}
|
|
889
|
+
const repositories: WorktreeRepositoryResult[] = [];
|
|
890
|
+
const indexing: Promise<void>[] = [];
|
|
891
|
+
const progress = options.streamInstall
|
|
892
|
+
? (line: string) => process.stderr.write(`${line}\n`)
|
|
893
|
+
: undefined;
|
|
894
|
+
for (const plan of plans) {
|
|
895
|
+
// oxlint-disable-next-line no-await-in-loop -- one repository at a time, installs included
|
|
896
|
+
const result = await realize(companionPath, plan, options, git, deps, warnings);
|
|
897
|
+
repositories.push(result);
|
|
898
|
+
if (result.index.reason === NOT_CREATED) continue;
|
|
899
|
+
// Indexing overlaps the next repository's setup; only the report waits for it.
|
|
900
|
+
indexing.push(
|
|
901
|
+
indexWorktree(plan.checkout, plan.target, companionPath, deps.tokensave, (action) =>
|
|
902
|
+
progress?.(`${plan.repository}: tokensave ${action} of ${plan.target}…`),
|
|
903
|
+
).then((index) => {
|
|
904
|
+
result.index = index;
|
|
905
|
+
}),
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
// After its children exist, so the folder is linked only once it holds a worktree.
|
|
909
|
+
const held = plans.flatMap((plan, at) =>
|
|
910
|
+
plan.umbrella && repositories[at]!.install.reason !== NOT_CREATED ? [plan.repository] : [],
|
|
911
|
+
);
|
|
912
|
+
const umbrella =
|
|
913
|
+
mirror && held.length > 0
|
|
914
|
+
? await realizeMirror(companionPath, mirror, held, deps, warnings)
|
|
915
|
+
: undefined;
|
|
916
|
+
// An unlinked mirror is reported broken; it gets no index. It holds the children's
|
|
917
|
+
// worktrees, so it is indexed after theirs rather than over them.
|
|
918
|
+
if (umbrella && mirror && !umbrella.error) {
|
|
919
|
+
const children = Promise.all(indexing);
|
|
920
|
+
indexing.push(
|
|
921
|
+
children
|
|
922
|
+
.then(() =>
|
|
923
|
+
indexWorktree(
|
|
924
|
+
mirror.umbrella,
|
|
925
|
+
mirror.folder,
|
|
926
|
+
companionPath,
|
|
927
|
+
deps.tokensave,
|
|
928
|
+
(action) => progress?.(`${mirror.umbrella}: tokensave ${action} of ${mirror.folder}…`),
|
|
929
|
+
UMBRELLA_NOT_INDEXED,
|
|
930
|
+
),
|
|
931
|
+
)
|
|
932
|
+
.then((index) => {
|
|
933
|
+
umbrella.index = index;
|
|
934
|
+
}),
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
await Promise.all(indexing);
|
|
938
|
+
for (const result of repositories) {
|
|
939
|
+
if (result.index.outcome === "failed") {
|
|
940
|
+
warnings.push(`${result.repository}: tokensave index step failed: ${result.index.reason}`);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
if (umbrella?.index.outcome === "failed") {
|
|
944
|
+
warnings.push(`${umbrella.path}: tokensave index step failed: ${umbrella.index.reason}`);
|
|
945
|
+
}
|
|
946
|
+
return {
|
|
947
|
+
workset: worksetId,
|
|
948
|
+
ok: repositories.every((entry) => !entry.error) && !umbrella?.error,
|
|
949
|
+
repositories,
|
|
950
|
+
...(umbrella ? { umbrella } : {}),
|
|
951
|
+
diagnostics,
|
|
952
|
+
warnings,
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* Links the mirrored worktree folder under the umbrella's id, without the companion
|
|
958
|
+
* registry, and wraps it for the umbrella's runtimes. Its children get neither: the
|
|
959
|
+
* folder's projection serves them, as the umbrella's serves its own.
|
|
960
|
+
*/
|
|
961
|
+
async function realizeMirror(
|
|
962
|
+
companionPath: string,
|
|
963
|
+
mirror: Mirror,
|
|
964
|
+
repositories: string[],
|
|
965
|
+
deps: WorktreeDeps,
|
|
966
|
+
warnings: string[],
|
|
967
|
+
): Promise<UmbrellaWorktreeResult> {
|
|
968
|
+
const { wrap, error, warning } = await linkAndWrap(
|
|
969
|
+
companionPath,
|
|
970
|
+
{ id: mirror.repositoryId, path: mirror.folder },
|
|
971
|
+
mirror.umbrella,
|
|
972
|
+
mirror.reuse,
|
|
973
|
+
deps,
|
|
974
|
+
);
|
|
975
|
+
if (warning) warnings.push(`${mirror.folder}: ${warning}`);
|
|
976
|
+
return {
|
|
977
|
+
path: mirror.umbrella,
|
|
978
|
+
worktree: mirror.folder,
|
|
979
|
+
action: mirror.reuse ? "reused" : "created",
|
|
980
|
+
repositories,
|
|
981
|
+
wrap,
|
|
982
|
+
index: { outcome: "skipped", ...(error ? { reason: "mirrored worktree broken" } : {}) },
|
|
983
|
+
...(error ? { error } : {}),
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Links `repository.path` to the companion and wraps it like `wrappedFrom`. A reused
|
|
989
|
+
* folder still wrapped from before stays usable, so a failed refresh only warns.
|
|
990
|
+
*/
|
|
991
|
+
async function linkAndWrap(
|
|
992
|
+
companionPath: string,
|
|
993
|
+
repository: LinkedRepository,
|
|
994
|
+
wrappedFrom: string,
|
|
995
|
+
reuse: boolean,
|
|
996
|
+
deps: WorktreeDeps,
|
|
997
|
+
): Promise<{ wrap: WrapOutcome; error?: string; warning?: string }> {
|
|
998
|
+
try {
|
|
999
|
+
await (deps.writeLink ?? writeRepoLocalRegistryEntry)(
|
|
1000
|
+
repository.path,
|
|
1001
|
+
companionPath,
|
|
1002
|
+
repository,
|
|
1003
|
+
"existing",
|
|
1004
|
+
);
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
return {
|
|
1007
|
+
wrap: { runtimes: [], outcome: "skipped", reason: "worktree not linked" },
|
|
1008
|
+
error: `linking the worktree failed: ${errorMessage(error)}`,
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
const wrap = await wrapWorktree(companionPath, wrappedFrom, repository, deps);
|
|
1012
|
+
if (wrap.outcome !== "failed") return { wrap };
|
|
1013
|
+
const message = `wrapping the worktree failed: ${wrap.reason}`;
|
|
1014
|
+
if (reuse && (await stillWrapped(repository.path, wrap.runtimes, deps))) {
|
|
1015
|
+
return { wrap, warning: `${message}; its earlier wrap stays` };
|
|
1016
|
+
}
|
|
1017
|
+
return { wrap, error: message };
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
async function realize(
|
|
1021
|
+
companionPath: string,
|
|
1022
|
+
plan: Plan,
|
|
1023
|
+
options: CreateWorktreesOptions,
|
|
1024
|
+
git: GitRunner,
|
|
1025
|
+
deps: WorktreeDeps,
|
|
1026
|
+
warnings: string[],
|
|
1027
|
+
): Promise<WorktreeRepositoryResult> {
|
|
1028
|
+
const result: WorktreeRepositoryResult = {
|
|
1029
|
+
repository: plan.repository,
|
|
1030
|
+
checkout: plan.checkout,
|
|
1031
|
+
path: plan.target,
|
|
1032
|
+
branch: plan.branch,
|
|
1033
|
+
action: plan.reuse ? "reused" : "created",
|
|
1034
|
+
install: { command: null, outcome: "skipped" },
|
|
1035
|
+
wrap: { runtimes: [], outcome: "skipped" },
|
|
1036
|
+
index: { outcome: "skipped" },
|
|
1037
|
+
include: { sources: [], copied: [], failed: [] },
|
|
1038
|
+
missingEnv: [],
|
|
1039
|
+
};
|
|
1040
|
+
if (!plan.reuse) {
|
|
1041
|
+
const failure = plan.take
|
|
1042
|
+
? await takeIntoWorktree(git, plan, warnings)
|
|
1043
|
+
: await addWorktree(git, plan);
|
|
1044
|
+
if (failure) {
|
|
1045
|
+
return {
|
|
1046
|
+
...result,
|
|
1047
|
+
install: { ...result.install, reason: NOT_CREATED },
|
|
1048
|
+
wrap: { ...result.wrap, reason: NOT_CREATED },
|
|
1049
|
+
index: { outcome: "skipped", reason: NOT_CREATED },
|
|
1050
|
+
error: failure,
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
if (plan.umbrella) {
|
|
1055
|
+
result.wrap.reason = "served by the mirrored worktree";
|
|
1056
|
+
} else {
|
|
1057
|
+
// The main checkout's id: a session moved here keeps its `MATE_REPOSITORY_ID`.
|
|
1058
|
+
const linked = await linkAndWrap(
|
|
1059
|
+
companionPath,
|
|
1060
|
+
{ id: plan.repositoryId, path: plan.target },
|
|
1061
|
+
plan.checkout,
|
|
1062
|
+
plan.reuse,
|
|
1063
|
+
deps,
|
|
1064
|
+
);
|
|
1065
|
+
result.wrap = linked.wrap;
|
|
1066
|
+
if (linked.error) result.error = linked.error;
|
|
1067
|
+
if (linked.warning) warnings.push(`${plan.repository}: ${linked.warning}`);
|
|
1068
|
+
}
|
|
1069
|
+
// Before install: a copied `.npmrc` may be what lets it reach a private registry.
|
|
1070
|
+
const selection = await selectIncludedFiles(git, plan.checkout);
|
|
1071
|
+
for (const warning of selection.warnings) warnings.push(`${plan.repository}: ${warning}`);
|
|
1072
|
+
result.include = await copyIncludedFiles(plan.checkout, plan.target, selection);
|
|
1073
|
+
if (result.include.failed.length > 0) {
|
|
1074
|
+
result.error ??= `copying ${result.include.failed.map((entry) => entry.path).join(", ")} failed`;
|
|
1075
|
+
}
|
|
1076
|
+
const command = await installCommand(plan.target);
|
|
1077
|
+
result.install.command = command ? command.join(" ") : null;
|
|
1078
|
+
if (plan.reuse) result.install.reason = "reused worktree";
|
|
1079
|
+
else if (!options.install) result.install.reason = "--no-install";
|
|
1080
|
+
else if (!command) result.install.reason = "no lockfile";
|
|
1081
|
+
else {
|
|
1082
|
+
const ok = await (deps.install ?? runInstall)(plan.target, command, options.streamInstall);
|
|
1083
|
+
result.install.outcome = ok ? "ok" : "failed";
|
|
1084
|
+
if (!ok) result.error ??= `${command.join(" ")} failed`;
|
|
1085
|
+
}
|
|
1086
|
+
// The caller indexes after install, regardless of `--no-install`: the index is not a dependency install.
|
|
1087
|
+
result.missingEnv = await missingEnvFiles(git, plan.checkout, plan.target);
|
|
1088
|
+
return result;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
async function stillWrapped(
|
|
1092
|
+
worktree: string,
|
|
1093
|
+
runtimes: readonly WrapRuntime[],
|
|
1094
|
+
deps: WorktreeDeps,
|
|
1095
|
+
): Promise<boolean> {
|
|
1096
|
+
try {
|
|
1097
|
+
const own = await wrappedRuntimes(worktree, deps);
|
|
1098
|
+
return runtimes.every((runtime) => own.includes(runtime));
|
|
1099
|
+
} catch {
|
|
1100
|
+
return false;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
/** Whether `cwd` is the worktree or lies inside it. */
|
|
1105
|
+
async function holds(worktree: string, cwd: string): Promise<boolean> {
|
|
1106
|
+
const relative = path.relative(worktree, await canonical(cwd));
|
|
1107
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
/** Why a worktree must stay, or null when it is clean and every commit is on a remote. */
|
|
1111
|
+
async function keepReason(
|
|
1112
|
+
git: GitRunner,
|
|
1113
|
+
listed: WorktreeEntry,
|
|
1114
|
+
cwd: string,
|
|
1115
|
+
): Promise<string | null> {
|
|
1116
|
+
if (listed.locked) return "locked";
|
|
1117
|
+
if (listed.stale) return `stale worktree entry (${listed.stale}); run \`git worktree prune\``;
|
|
1118
|
+
const worktree = listed.path;
|
|
1119
|
+
if (await holds(worktree, cwd)) return "in use (current directory)";
|
|
1120
|
+
const status = await git(worktree, ["status", "--porcelain"]);
|
|
1121
|
+
if (status.code !== 0) return `cannot read its status: ${status.stderr.trim()}`;
|
|
1122
|
+
if (status.stdout.trim()) return "uncommitted changes or untracked files";
|
|
1123
|
+
const unpushed = await git(worktree, ["log", "--oneline", "HEAD", "--not", "--remotes"]);
|
|
1124
|
+
if (unpushed.code !== 0) return `cannot read its commits: ${unpushed.stderr.trim()}`;
|
|
1125
|
+
if (unpushed.stdout.trim()) return "commits on no remote";
|
|
1126
|
+
return null;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
/** Recorded Delivery Branches per Working Repository; not-applicable deliveries name none. */
|
|
1130
|
+
async function recordedBranches(
|
|
1131
|
+
companionPath: string,
|
|
1132
|
+
changes: readonly string[],
|
|
1133
|
+
warnings: string[],
|
|
1134
|
+
): Promise<Map<string, Set<string>>> {
|
|
1135
|
+
const byRepository = new Map<string, Set<string>>();
|
|
1136
|
+
for (const change of changes) {
|
|
1137
|
+
// oxlint-disable-next-line no-await-in-loop -- a few small files, in order
|
|
1138
|
+
const location = await locateChange(companionPath, change);
|
|
1139
|
+
if (!location) continue;
|
|
1140
|
+
let record: DeliveryRecord | null;
|
|
1141
|
+
try {
|
|
1142
|
+
// oxlint-disable-next-line no-await-in-loop -- a few small files, in order
|
|
1143
|
+
record = await readDeliveryRecord(location.dir);
|
|
1144
|
+
} catch (error) {
|
|
1145
|
+
warnings.push(`${change}: cannot read its Delivery Record: ${errorMessage(error)}`);
|
|
1146
|
+
continue;
|
|
1147
|
+
}
|
|
1148
|
+
for (const delivery of record?.deliveries ?? []) {
|
|
1149
|
+
if (!delivery.branch || delivery.notApplicable) continue;
|
|
1150
|
+
const branches = byRepository.get(delivery.repository) ?? new Set<string>();
|
|
1151
|
+
branches.add(delivery.branch);
|
|
1152
|
+
byRepository.set(delivery.repository, branches);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
return byRepository;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/** Returns the Umbrella Repository whose child the repository is, so its mirror is pruned after. */
|
|
1159
|
+
async function pruneRepository(
|
|
1160
|
+
companionPath: string,
|
|
1161
|
+
worksetId: string,
|
|
1162
|
+
repository: string,
|
|
1163
|
+
branches: ReadonlySet<string>,
|
|
1164
|
+
index: LinkedIndex,
|
|
1165
|
+
git: GitRunner,
|
|
1166
|
+
deps: WorktreeDeps,
|
|
1167
|
+
result: PruneResult,
|
|
1168
|
+
): Promise<LinkedCheckout | undefined> {
|
|
1169
|
+
const { linked } = linkedCheckout(index, repository);
|
|
1170
|
+
if (!linked) return undefined;
|
|
1171
|
+
const entries = await listWorktrees(git, linked.path);
|
|
1172
|
+
const main = entries?.[0];
|
|
1173
|
+
if (!main) {
|
|
1174
|
+
result.warnings.push(`${repository}: cannot list the worktrees of ${linked.path}`);
|
|
1175
|
+
return linked.umbrella ? linked : undefined;
|
|
1176
|
+
}
|
|
1177
|
+
// The first entry is the main checkout; a detached HEAD has no branch and never matches.
|
|
1178
|
+
const candidates = entries
|
|
1179
|
+
.slice(1)
|
|
1180
|
+
.filter((entry) => entry.branch !== null && branches.has(entry.branch));
|
|
1181
|
+
for (const listed of candidates) {
|
|
1182
|
+
// oxlint-disable-next-line no-await-in-loop -- Git operations on one checkout, one at a time
|
|
1183
|
+
await pruneWorktree(
|
|
1184
|
+
companionPath,
|
|
1185
|
+
{ worksetId, repository, main: main.path, linked, listed },
|
|
1186
|
+
git,
|
|
1187
|
+
deps,
|
|
1188
|
+
result,
|
|
1189
|
+
);
|
|
1190
|
+
}
|
|
1191
|
+
return linked.umbrella ? linked : undefined;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
interface PruneCandidate {
|
|
1195
|
+
worksetId: string;
|
|
1196
|
+
repository: string;
|
|
1197
|
+
/** The main checkout's path. */
|
|
1198
|
+
main: string;
|
|
1199
|
+
linked: LinkedCheckout;
|
|
1200
|
+
listed: WorktreeEntry;
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
async function pruneWorktree(
|
|
1204
|
+
companionPath: string,
|
|
1205
|
+
candidate: PruneCandidate,
|
|
1206
|
+
git: GitRunner,
|
|
1207
|
+
deps: WorktreeDeps,
|
|
1208
|
+
result: PruneResult,
|
|
1209
|
+
): Promise<void> {
|
|
1210
|
+
const { worksetId, repository, main, linked, listed } = candidate;
|
|
1211
|
+
const target = listed.path;
|
|
1212
|
+
const entry = { workset: worksetId, repository, path: target };
|
|
1213
|
+
const cwd = (deps.cwd ?? process.cwd)();
|
|
1214
|
+
const reason = await keepReason(git, listed, cwd);
|
|
1215
|
+
if (reason) {
|
|
1216
|
+
result.kept.push({ ...entry, reason });
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
// A worktree in the mirrored folder carries no wrap; the folder is unwrapped after.
|
|
1220
|
+
const inMirror =
|
|
1221
|
+
linked.umbrella !== undefined &&
|
|
1222
|
+
path.dirname(target) === (await canonical(worktreePathFor(linked.umbrella, worksetId)));
|
|
1223
|
+
if (!inMirror) {
|
|
1224
|
+
// Unwrap first: machine-local state keyed by its path (Claude local-scope MCP) must not outlive it.
|
|
1225
|
+
try {
|
|
1226
|
+
await (deps.unwrap ?? cleanupWorkingRepository)(target, [companionPath]);
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
result.kept.push({ ...entry, reason: `removing its wrap failed: ${errorMessage(error)}` });
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
const removed = await git(main, ["worktree", "remove", target]);
|
|
1233
|
+
if (removed.code === 0) {
|
|
1234
|
+
result.removed.push(entry);
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
const refused = removed.stderr.trim() || "git refused";
|
|
1238
|
+
if (inMirror) {
|
|
1239
|
+
result.kept.push({ ...entry, reason: refused });
|
|
1240
|
+
return;
|
|
1241
|
+
}
|
|
1242
|
+
// The umbrella's id is no link for a child's own worktree, so Mate cannot re-wrap it.
|
|
1243
|
+
if (linked.umbrella) {
|
|
1244
|
+
result.kept.push({
|
|
1245
|
+
...entry,
|
|
1246
|
+
reason: `${refused}; its wrap was removed, run \`${FRAMEWORK_NAME} wrap\` there`,
|
|
1247
|
+
});
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
// Kept, so it gets its guardrails back.
|
|
1251
|
+
const rewrap = await wrapWorktree(companionPath, main, { id: linked.id, path: target }, deps);
|
|
1252
|
+
result.kept.push({
|
|
1253
|
+
...entry,
|
|
1254
|
+
reason:
|
|
1255
|
+
rewrap.outcome === "failed"
|
|
1256
|
+
? `${refused}; re-wrapping it failed, run \`${FRAMEWORK_NAME} wrap\` there: ${rewrap.reason}`
|
|
1257
|
+
: refused,
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* Removes the worktrees of the given (Done) Worksets that are clean and fully pushed,
|
|
1263
|
+
* without `--force`, and never deletes a branch. A worktree belongs to a Workset when it is
|
|
1264
|
+
* a linked worktree with a Delivery Branch of the Workset's changes checked out, wherever
|
|
1265
|
+
* it lives. The main checkout and a worktree holding the working directory stay, as does
|
|
1266
|
+
* every other worktree. Each is unwrapped before removal.
|
|
1267
|
+
*/
|
|
1268
|
+
export async function pruneWorksetWorktrees(
|
|
1269
|
+
companionPath: string,
|
|
1270
|
+
done: readonly PruneTarget[],
|
|
1271
|
+
deps: WorktreeDeps = {},
|
|
1272
|
+
): Promise<PruneResult> {
|
|
1273
|
+
const git = deps.git ?? runGit;
|
|
1274
|
+
const result: PruneResult = { removed: [], kept: [], warnings: [] };
|
|
1275
|
+
let index: LinkedIndex | undefined;
|
|
1276
|
+
for (const workset of done) {
|
|
1277
|
+
// oxlint-disable-next-line no-await-in-loop -- Worksets one at a time
|
|
1278
|
+
const branches = await recordedBranches(companionPath, workset.changes, result.warnings);
|
|
1279
|
+
if (branches.size === 0) continue;
|
|
1280
|
+
// oxlint-disable-next-line no-await-in-loop -- read once, on first need
|
|
1281
|
+
index ??= await linkedIndex(companionPath, git, (deps.cwd ?? process.cwd)());
|
|
1282
|
+
// Umbrella path to its Repository Link id.
|
|
1283
|
+
const umbrellas = new Map<string, string>();
|
|
1284
|
+
for (const [repository, names] of branches) {
|
|
1285
|
+
// oxlint-disable-next-line no-await-in-loop -- Git operations on shared checkouts, one at a time
|
|
1286
|
+
const child = await pruneRepository(
|
|
1287
|
+
companionPath,
|
|
1288
|
+
workset.id,
|
|
1289
|
+
repository,
|
|
1290
|
+
names,
|
|
1291
|
+
index,
|
|
1292
|
+
git,
|
|
1293
|
+
deps,
|
|
1294
|
+
result,
|
|
1295
|
+
);
|
|
1296
|
+
if (child?.umbrella) umbrellas.set(child.umbrella, child.id);
|
|
1297
|
+
}
|
|
1298
|
+
for (const [umbrella, repositoryId] of umbrellas) {
|
|
1299
|
+
// oxlint-disable-next-line no-await-in-loop -- after its children, one at a time
|
|
1300
|
+
await pruneMirror(
|
|
1301
|
+
companionPath,
|
|
1302
|
+
{ worksetId: workset.id, umbrella, repositoryId },
|
|
1303
|
+
deps,
|
|
1304
|
+
result,
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
return result;
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
/** Files the OS writes into any folder it shows, e.g. Finder's; never anyone's work. */
|
|
1312
|
+
const OS_METADATA = new Set([".DS_Store", "Thumbs.db", "desktop.ini"]);
|
|
1313
|
+
|
|
1314
|
+
/**
|
|
1315
|
+
* Top-level names a wrap, a link, or the OS may write; everything else in a mirrored
|
|
1316
|
+
* worktree is someone's work.
|
|
1317
|
+
*/
|
|
1318
|
+
function mirrorMaterial(): Set<string> {
|
|
1319
|
+
return new Set([
|
|
1320
|
+
...projectionEntries()
|
|
1321
|
+
.map((entry) => entry.path.split(/[\\/]/)[0]!)
|
|
1322
|
+
.filter((name) => name !== ".git" && name !== "~"),
|
|
1323
|
+
...OS_METADATA,
|
|
1324
|
+
]);
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* Best effort: unwraps and removes the Workset's mirrored worktree, then an empty
|
|
1329
|
+
* `<umbrella>.worktrees`, only when nothing but Mate's material is left. Never recursive,
|
|
1330
|
+
* never forced; a folder that stays is named with the reason.
|
|
1331
|
+
*/
|
|
1332
|
+
async function pruneMirror(
|
|
1333
|
+
companionPath: string,
|
|
1334
|
+
mirror: { worksetId: string; umbrella: string; repositoryId: string },
|
|
1335
|
+
deps: WorktreeDeps,
|
|
1336
|
+
result: PruneResult,
|
|
1337
|
+
): Promise<void> {
|
|
1338
|
+
const { worksetId, umbrella, repositoryId } = mirror;
|
|
1339
|
+
const folder = await canonical(worktreePathFor(umbrella, worksetId));
|
|
1340
|
+
// Only this companion's mirrored worktree, never a folder it does not own.
|
|
1341
|
+
if (!(await isMirrorOf(folder, companionPath, repositoryId))) return;
|
|
1342
|
+
const umbrellas = (result.umbrellas ??= { removed: [], kept: [] });
|
|
1343
|
+
const entry = { workset: worksetId, umbrella, path: folder };
|
|
1344
|
+
const keep = (reason: string): void => void umbrellas.kept.push({ ...entry, reason });
|
|
1345
|
+
if (await holds(folder, (deps.cwd ?? process.cwd)())) return keep("in use (current directory)");
|
|
1346
|
+
const material = mirrorMaterial();
|
|
1347
|
+
const listed = await fs.readdir(folder).catch(() => null);
|
|
1348
|
+
if (listed === null) return keep("cannot list its entries");
|
|
1349
|
+
const others = listed.filter((name) => !material.has(name)).toSorted();
|
|
1350
|
+
if (others.length > 0) return keep(`still holds ${others.join(", ")}`);
|
|
1351
|
+
try {
|
|
1352
|
+
await (deps.unwrap ?? cleanupWorkingRepository)(folder, [companionPath]);
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
return keep(`removing its wrap failed: ${errorMessage(error)}`);
|
|
1355
|
+
}
|
|
1356
|
+
// A failure shows below as what unwrapping left.
|
|
1357
|
+
await Promise.all(
|
|
1358
|
+
listed
|
|
1359
|
+
.filter((name) => OS_METADATA.has(name))
|
|
1360
|
+
.map((name) => fs.rm(path.join(folder, name), { force: true }).catch(() => undefined)),
|
|
1361
|
+
);
|
|
1362
|
+
try {
|
|
1363
|
+
await fs.rmdir(folder);
|
|
1364
|
+
} catch (error) {
|
|
1365
|
+
const left = await fs.readdir(folder).catch(() => []);
|
|
1366
|
+
const refused =
|
|
1367
|
+
left.length > 0
|
|
1368
|
+
? `unwrapping left ${left.toSorted().join(", ")}`
|
|
1369
|
+
: `removing it failed: ${errorMessage(error)}`;
|
|
1370
|
+
// Kept, so it gets its link and guardrails back, and a later prune finds it again.
|
|
1371
|
+
const restored = await linkAndWrap(
|
|
1372
|
+
companionPath,
|
|
1373
|
+
{ id: repositoryId, path: folder },
|
|
1374
|
+
umbrella,
|
|
1375
|
+
false,
|
|
1376
|
+
deps,
|
|
1377
|
+
);
|
|
1378
|
+
const failure = restored.error ?? restored.warning;
|
|
1379
|
+
return keep(
|
|
1380
|
+
failure
|
|
1381
|
+
? `${refused}; restoring it failed, run \`${FRAMEWORK_NAME} wrap\` there: ${failure}`
|
|
1382
|
+
: refused,
|
|
1383
|
+
);
|
|
1384
|
+
}
|
|
1385
|
+
umbrellas.removed.push(entry);
|
|
1386
|
+
// The parent stays while another Workset's mirror is in it.
|
|
1387
|
+
await fs.rmdir(path.dirname(folder)).catch(() => undefined);
|
|
1388
|
+
}
|