Compare commits

...
Author SHA1 Message Date
Cursor Agent 02cac6dd61 fix: use Effect.flatMap for decodeJjCurrentChange to route errors to typed channel
decodeJjCurrentChange was throwing VcsOutputDecodeError inside Effect.map,
which causes the error to become an unrecoverable defect rather than a typed
error in the VcsError channel. Changed the function to return an Effect and
use Effect.flatMap at the call site so errors properly land in the typed
error channel as the type signature promises.
2026-05-02 16:47:03 +00:00
Julius Marminge e2e40c24f1 Add typed jj extension surface 2026-05-02 09:34:41 -07:00
Julius Marminge ab974c882a Prefer jj detection and add ignore classifier capability
- Detect jj before git for colocated repositories
- Add ignoreClassifier to VCS capabilities
- Fix trace2 hook exit code reporting
2026-05-02 09:34:41 -07:00
Julius Marminge 29aa1ccaf8 Use effect file system and node services in VCS tests
- Replace ad hoc temp-dir handling with scoped FileSystem APIs
- Provide NodeServices in VCS driver and status broadcaster tests
- Normalize CWDs through FileSystem realpath
2026-05-02 09:34:41 -07:00
Julius Marminge c31becadc7 Add JJ VCS driver support
- Detect and route jj repositories alongside git
- Thread VCS kind through status and UI labels
- Add jj driver contract coverage and shared freshness helper
2026-05-02 09:34:41 -07:00
Julius Marminge 128b432bee Add generic source control provider routing core 2026-05-02 09:33:55 -07:00
Julius Marminge a73408c324 Handle empty GitHub PR listings and fallback branch lookup
- Treat empty `gh pr list` output as no results
- Fall back to `main` when provider default-branch detection fails
- Add coverage for PR creation fallback behavior
2026-05-02 00:03:12 -07:00
Cursor Agent 1e0a7598c7 fix: rename local sourceControlProvider to hostingProvider to avoid shadowing outer function
Applied via @cursor push command
2026-05-02 00:03:12 -07:00
Julius Marminge 8a5b784eae Scope VCS process lifetimes with a helper
- Replace raw spawn access with `withProcess` for scoped use
- Ensure child processes are finalized even on early exits
- Keep `run` built on the scoped helper for safer cleanup
2026-05-02 00:03:12 -07:00
Julius Marminge 7788858149 Expose spawned VCS process handles
- Add a reusable `spawn` API for VCS processes
- Factor stream collection into `collectText`
- Preserve existing `run` behavior on top of the new handle
2026-05-02 00:03:12 -07:00
Julius Marminge b743d0b66e Use typed exit codes in VCS process results
- Switch VCS process and git driver results to `ChildProcessSpawner.ExitCode`
- Update status checks and fallback results to use the new typed exit code
- Refresh tests to match the new result shape
2026-05-02 00:03:12 -07:00
Julius Marminge ccb97da75c Update git ref mock data for primary remote
- Rename branch fixtures to refs and primary remote flags
- Align Git actions and keybinding tests with new ref labels
2026-05-02 00:03:12 -07:00
Julius Marminge 3a254bad33 Normalize VCS CWDs and forward git env
- Resolve symlinked working directories before caching and workflow calls
- Pass execute env through the Git VCS driver
2026-05-02 00:03:12 -07:00
Julius Marminge a889dc68ca Refactor git services into source control layers
- Move GitManager and GitHubCli contracts/layers to their new modules
- Update server wiring and tests for the relocated pluggable git setup
2026-05-02 00:03:12 -07:00
Julius Marminge dcbb182f82 Extract text generation into dedicated server module
- Move git text-generation layers and tests under `src/textGeneration`
- Route server and provider drivers to the new module
- Replace the old git-scoped `TextGenerationLive` registry layer
2026-05-02 00:03:12 -07:00
Julius Marminge e21b1514a5 Rename git hosting provider fields to source control provider
- Rename shared/server status fields and detectors from hostingProvider to sourceControlProvider
- Move provider schema into contracts/sourceControl and update status/event tests
- Refresh branch toolbar labels from switchRef to checkout
2026-05-02 00:03:12 -07:00
Julius Marminge e795698818 Rename git APIs around refs
- Replace branch-centric git/VCS types and methods with ref-based names
- Update server, web, and tests to use the new pluggable integration shape
2026-05-02 00:03:12 -07:00
Julius Marminge 506e0fc049 Add pluggable source control provider detection
- Detect GitHub, GitLab, and Azure DevOps remotes in the shared parser
- Cache provider resolution and return unsupported stubs for unregistered kinds
- Remove deprecated git RPCs from the web IPC surface
2026-05-02 00:02:06 -07:00
Julius Marminge e8d67ffb91 Rename Array import alias in GitManager
- Use `Arr` alias for Effect Array in `GitManager`
- Keep pull request sorting logic unchanged
2026-05-02 00:02:06 -07:00
Julius Marminge c0e867b4d9 Sort pull requests by updated time and fix git mock shape
- Use Effect ordering for PR recency sorting in the server git manager
- Update web git status test mocks to match the split `vcs` and `git` APIs
2026-05-02 00:02:06 -07:00
Julius Marminge 6d7de0b314 Normalize timestamps across VCS and source control contracts
- Switch freshness and PR update times to typed `DateTime`/`Option` values
- Update GitHub and VCS adapters, tests, and sorting to use the new shapes
2026-05-02 00:02:06 -07:00
Julius Marminge 38185dc696 Add pluggable source control routing
- Route git workflows through source control providers
- Replace git status broadcaster with VCS status service
- Update orchestration, server, and web contracts for provider-aware git
2026-05-02 00:02:06 -07:00
Julius Marminge 87c2e3e1ef Use mock layers for Git VCS driver tests
- Replace ad hoc `succeed` casts with `Layer.mock` in integration and reactor tests
- Keep Git VCS driver fixtures type-safe while preserving existing test behavior
2026-05-02 00:02:06 -07:00
Julius Marminge 5c227dcaa7 Tighten VCS driver test assertions
- Switch integration and contract tests to Effect/Vitest assertions
- Avoid platform-specific realpath assumptions in repository identity checks
- Use Path service for portable test file and worktree path handling
2026-05-02 00:02:06 -07:00
Julius Marminge ccbad67c43 Refactor VCS driver tests into shared contract harness
- Add a reusable VCS driver contract suite
- Rework Git driver tests to use real repo fixtures
2026-05-02 00:02:06 -07:00
Julius Marminge 127e91bc86 Refactor GitVcsDriverCore test setup
- Simplify shared test helpers and temp repo setup
- Switch the test layer wiring to merge Node services
- Remove unused shell/process scaffolding from the spec
2026-05-02 00:02:06 -07:00
Julius Marminge e01c92ff0a Add VCS driver registry for pluggable git integration
- Route checkpointing and workspace services through a VCS driver registry
- Split git driver construction from the driver service wrapper
- Update tests and harnesses to mock the registry instead of the raw driver
2026-05-02 00:02:06 -07:00
Julius Marminge a11d6b92ea Refactor git core into pluggable VCS driver
- Move low-level git service into `GitVcsDriverCore`
- Update server wiring and tests to use the new driver
2026-05-02 00:02:06 -07:00
Julius Marminge 82a8394cd8 Split git VCS driver from core service
- Introduce a dedicated `GitVcsDriver` service and `vcsLayer`
- Update server, orchestration, and workspace wiring to use the new layer
- Adjust tests and mocks for the new git-specific dependency
2026-05-02 00:02:06 -07:00
Julius Marminge 0ce293b37e Use Effect time APIs for VCS and workspace scans
- Switch freshness and scan timestamps to `DateTime.now` from Effect
- Keep timestamps consistent within each async operation
2026-05-02 00:02:06 -07:00
Julius Marminge 0b0d98c1fd Fix GitVcsDriver test dependency import
- Import `VcsProcess` as a namespace in the test
- Update layer injection to target `VcsProcess.VcsProcess`
2026-05-02 00:02:06 -07:00
Julius Marminge ecac3ac795 Use VcsProcess module directly in tests
- Remove the aliased service import
- Reference `VcsProcess.VcsProcess` explicitly in checkpoint and workspace tests
2026-05-02 00:02:06 -07:00
Julius Marminge 5e0327dee6 Standardize VCS layer imports across server tests
- Switch GitVcsDriver and VcsProcess usages to namespace imports
- Update server and integration wiring to use `.layer` consistently
- Keep test type annotations aligned with the exported service types
2026-05-02 00:02:06 -07:00
Julius Marminge 8f09b8d0ab Refactor VCS layers into top-level modules
- Move VcsDriver and VcsProcess out of nested service/layer paths
- Update server, workspace, orchestration, and tests to use new exports
- Rename layer exports to `layer` for consistency
2026-05-02 00:02:06 -07:00
Julius Marminge 972a6876b8 Introduce pluggable VCS driver for git operations
- Replace direct GitCore dependencies with VcsDriver and VcsProcess
- Move checkpointing, workspace, and orchestration flows onto the new VCS abstraction
- Drop workspace-specific git helpers from GitCore
2026-05-02 00:02:06 -07:00
Julius Marminge 0cd920f32e Add version control foundation plans
- Add phase 1 VCS driver plan
- Add phase 2 source control provider plan
- Index both plans in `.plans/README.md`
2026-05-02 00:02:06 -07:00
112 changed files with 7104 additions and 5333 deletions

No files matched your search

@@ -0,0 +1,216 @@
# Version Control Phase 1: VCS Driver Foundation
## Goal
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
## Scope
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
- Add server services under `apps/server/src/vcs`:
- `Services/VcsDriver.ts`
- `Services/VcsRepositoryResolver.ts`
- `Services/VcsProcess.ts`
- `Layers/GitVcsDriver.ts`
- `errors.ts`
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
## Non-Goals
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
- No T3 Review implementation yet.
- No broad UI redesign.
## Driver Model
Use provider-neutral nouns in new APIs:
- `VcsDriver`: local repository mechanics.
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
- `RefName`: branch, bookmark, tag, or provider-specific ref.
The initial driver capabilities should be explicit:
```ts
export interface VcsDriverCapabilities {
readonly kind: "git" | "jj" | "sapling" | "unknown";
readonly supportsWorktrees: boolean;
readonly supportsBookmarks: boolean;
readonly supportsAtomicSnapshot: boolean;
readonly supportsPushDefaultRemote: boolean;
}
```
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
- `detectRepository(cwd)`
- `status(cwd, options)`
- `listRefs(cwd, query/pagination)`
- `checkoutRef(cwd, ref)`
- `createRef(cwd, ref, from?)`
- `createWorkspace(cwd, ref, path?)`
- `removeWorkspace(path)`
- `prepareChangeContext(cwd, filePaths?)`
- `createChange(cwd, message, options)`
- `push(cwd, target?)`
- `rangeContext(cwd, base, head)`
- `listWorkspaceFiles(cwd, options)`
## Effect Process Layer
Create a small reusable `VcsProcess` service instead of using `runProcess`.
Requirements:
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
- Support scoped acquisition/release for long-running commands and interruption.
- Support bounded stdout/stderr collection with truncation markers.
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
- Support stdin.
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
- Stream output lines to progress callbacks as Effects.
- Return a typed `ProcessOutput` value for successful execution.
- Fail with typed errors, not generic thrown exceptions.
Errors should be schema-backed tagged classes, for example:
- `VcsProcessSpawnError`
- `VcsProcessExitError`
- `VcsProcessTimeoutError`
- `VcsOutputDecodeError`
- `VcsRepositoryDetectionError`
- `VcsUnsupportedOperationError`
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
## Git Driver Rewrite
Rewrite Git support against `VcsProcess`.
Carry forward current behavior from:
- `apps/server/src/git/Layers/GitCore.ts`
- `apps/server/src/git/Layers/GitCore.test.ts`
- current Git status/branch/worktree contracts
But split the implementation into smaller modules:
- command execution and hardening config
- repository detection
- status parsing
- branch/ref parsing
- worktree operations
- commit/range context generation
- push/pull operations
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
## Freshness and Local Caching
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
Treat these as live/local:
- repository detection for the active cwd
- working copy dirty state
- staged/unstaged/untracked file summaries
- current branch/bookmark/change name
- local branch/bookmark lists
- local worktree/workspace lists
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
Treat these as cached or explicit-refresh only:
- remote tracking branch refreshes
- ahead/behind counts that require network fetches
- default branch discovery from a remote provider
- remote branch lists beyond locally known refs
The VCS driver should expose freshness metadata with status results:
```ts
export interface VcsFreshness {
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
readonly observedAt: string;
readonly expiresAt?: string;
}
```
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
Use Effect `Cache` for repository identity and expensive local metadata:
- key by resolved repository root plus VCS kind
- invalidate on cwd/root changes and workspace mutation operations
- use short TTLs for local status caches when filesystem events are unavailable
- never hide command failures behind stale values unless the caller explicitly accepts stale data
## Cutover Policy
Prefer direct migration and deletion over compatibility wrappers.
Rules:
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
- No new feature work may depend on transitional modules.
Expected transitional candidates:
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
## Tests
Add integration-style tests with real temporary Git repositories for the new Git driver:
- non-repository detection
- status for clean/dirty/untracked/staged states
- branch/ref list with pagination
- checkout/create branch
- worktree create/remove
- commit context generation with file filters
- commit creation with hook progress events
- push behavior against a local bare remote
- status polling does not perform remote network refresh by default
- concurrent duplicate status requests are coalesced
- bounded output/truncation
- timeout/interruption
- typed error shape for command failure and missing executable
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
## Migration Steps
1. Add `vcs` contracts and tagged errors.
2. Add `VcsProcess` and unit tests around process execution semantics.
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
4. Implement `GitVcsDriver` with real Git command integration tests.
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
6. Move commit/range/push callers to the VCS service directly.
7. Delete migrated `GitCore` internals and tests as each caller group moves.
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
## Acceptance Criteria
- Current Git branch/status/worktree/commit behavior remains intact.
- New Git implementation does not depend on `processRunner.ts`.
- New errors are typed and inspectable by tests.
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Background status refresh is local-only by default and cannot hit provider rate limits.
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
@@ -0,0 +1,268 @@
# Version Control Phase 2: Source Control Provider Foundation
## Goal
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
## Scope
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
- Add server services under `apps/server/src/sourceControl`:
- `Services/SourceControlProvider.ts`
- `Services/SourceControlProviderRegistry.ts`
- `Services/SourceControlProcess.ts`
- `Layers/GitHubSourceControlProvider.ts`
- `errors.ts`
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
## Non-Goals
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
- No in-app review UI yet.
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
## Provider Model
Use provider-neutral names:
- `SourceControlProvider`: hosted repository and change-request mechanics.
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
- `ChangeRequestThread`: review or discussion thread.
- `ChangeRequestComment`: top-level or inline comment.
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
Core provider operations:
- `detectRemote(remoteUrl)`
- `checkAuth(cwd)`
- `getRepository(cwd | remoteUrl)`
- `getDefaultTargetRef(repository)`
- `listChangeRequests(repository, filters)`
- `getChangeRequest(repository, reference)`
- `createChangeRequest(repository, input)`
- `checkoutChangeRequest(cwd, changeRequest, options)`
- `getCloneUrls(repository)`
Review-facing operations should be designed now, even if unimplemented:
- `listReviewThreads(changeRequest)`
- `createReviewComment(changeRequest, input)`
- `replyToReviewThread(thread, input)`
- `resolveReviewThread(thread)`
- `submitReview(changeRequest, input)`
Each operation should be guarded by capabilities:
```ts
export interface SourceControlProviderCapabilities {
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
readonly supportsCreateChangeRequest: boolean;
readonly supportsCheckoutChangeRequest: boolean;
readonly supportsReviewThreads: boolean;
readonly supportsInlineComments: boolean;
readonly supportsDraftChangeRequests: boolean;
}
```
## Provider Registry
Add a registry that resolves a provider from repository remotes and explicit user input.
Rules:
- Detection should be pure where possible and testable without spawning CLIs.
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
## Rate Limits and Provider Caching
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
Default behavior:
- Pure URL/remote parsing is always live because it is local.
- Provider detection from local remotes is live-local.
- Authentication checks are cached.
- Repository metadata is cached.
- Default branch metadata is cached.
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
- Create/update operations invalidate affected cache keys immediately after success.
The provider API should make freshness explicit:
```ts
export interface SourceControlFreshness {
readonly source: "live-local" | "cached-provider" | "live-provider";
readonly observedAt: string;
readonly expiresAt?: string;
readonly stale?: boolean;
}
export type ProviderRefreshPolicy =
| "cache-first"
| "stale-while-revalidate"
| "force-refresh"
| "local-only";
```
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
Use Effect `Cache` for provider data:
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
Provider drivers should surface rate-limit signals when available:
- remaining quota
- reset time
- retry-after duration
- whether the limit is primary, secondary/abuse, or unknown
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
Avoid rate-limit footguns:
- no provider calls from render loops or fast status polling
- no listing all PRs/MRs across all repos to infer one branch state
- no silent GitHub fallback for unknown providers
- no unbounded cache cardinality for branch names or free-form search queries
- no per-thread duplicate provider refresh when multiple views observe the same repository
## GitHub Provider Rewrite
Rewrite GitHub support as `GitHubSourceControlProvider`.
Carry forward behavior from:
- `apps/server/src/git/Layers/GitHubCli.ts`
- `apps/server/src/git/Layers/GitHubCli.test.ts`
- `apps/server/src/git/githubPullRequests.ts`
- GitHub-specific `GitManager` PR paths
Implementation requirements:
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
- Keep stdout/stderr bounded.
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
## GitManager Cutover
Refactor `GitManager` so it coordinates three independent services:
- `VcsDriver` for local repository mechanics.
- `SourceControlProviderRegistry` for hosted provider selection.
- `TextGeneration` for message/body generation.
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
The Commit + PR flow should become:
1. Resolve VCS repository and local status.
2. Resolve source-control provider from remotes.
3. Generate commit content through the existing text generation service.
4. Create local change through `VcsDriver`.
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
6. Generate change-request title/body.
7. Create the change request through `SourceControlProvider`.
## Cutover Policy
This phase should aggressively remove old GitHub-specific internals.
Rules:
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
## GitLab and Azure Readiness
Use the triaged references as implementation inputs, not merge targets:
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
The abstraction should let Phase 3 add:
- `GitLabSourceControlProvider` using `glab`.
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
No provider should need to edit GitHub code to join the registry.
## T3 Review Design Constraint
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
That means contracts should include stable IDs and enough metadata for:
- file-level diffs
- inline review threads
- resolved/unresolved state
- top-level discussion comments
- pending review submission
- provider URL back-links
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
## Tests
Add tests at three levels:
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
Required cases:
- GitHub PR URL, number, and branch-ish references.
- GitLab MR URL/reference parsing.
- Azure DevOps PR URL parsing for same-repo URLs.
- unknown provider returns unsupported-operation errors.
- missing CLI and auth failures produce distinct typed errors.
- invalid CLI JSON fails at decode boundary with useful context.
## Migration Steps
1. Add `sourceControl` contracts and provider-neutral schemas.
2. Add shared remote/reference parser helpers and tests.
3. Add `SourceControlProcess` and provider errors.
4. Add provider registry with GitHub-only registration.
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
## Acceptance Criteria
- Existing GitHub Commit + PR and PR checkout flows still work.
- `GitManager` no longer imports or depends on `GitHubCli`.
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
- Unknown/unsupported providers fail explicitly and visibly.
- GitHub command execution does not depend on `processRunner.ts`.
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
- Rate-limit responses become typed errors with retry/reset metadata where available.
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
+2
View File
@@ -10,3 +10,5 @@
8. `08-precommit-format-and-lint.md`
9. `09-event-state-test-expansion.md`
10. `10-unify-process-session-abstraction.md`
19. `19-version-control-phase-1-vcs-driver-foundation.md`
20. `20-version-control-phase-2-source-control-provider-foundation.md`
@@ -25,10 +25,7 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
@@ -77,6 +74,11 @@ import {
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -291,7 +293,7 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(providerEventLoggersLayer),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
projectionSnapshotQueryLayer,
@@ -307,31 +309,32 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
});
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(gitWorkflowLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -342,11 +345,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(VcsDriverRegistry.layer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(VcsProcess.layer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
+2 -5
View File
@@ -1,6 +1,6 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import type { VcsError } from "@t3tools/contracts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
@@ -35,9 +35,6 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
}
}
export type CheckpointStoreError =
| GitCommandError
| CheckpointInvariantError
| CheckpointUnavailableError;
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
@@ -8,24 +8,27 @@ import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } from "@t3tools/contracts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import type { VcsError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ThreadId } from "@t3tools/contracts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-store-test-",
});
const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfigLayer),
Layer.provide(NodeServices.layer),
);
const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
Layer.provide(GitCoreTestLayer),
Layer.provide(NodeServices.layer),
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = CheckpointStoreTestLayer.pipe(
Layer.provideMerge(VcsProcessTestLayer),
Layer.provideMerge(VcsDriverTestLayer),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
function makeTmpDir(
prefix = "checkpoint-store-test-",
@@ -49,11 +52,12 @@ function writeTextFile(
function git(
cwd: string,
args: ReadonlyArray<string>,
): Effect.Effect<string, GitCommandError, GitCore> {
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
const process = yield* VcsProcess.VcsProcess;
const result = yield* process.run({
operation: "CheckpointStore.test.git",
command: "git",
cwd,
args,
timeoutMs: 10_000,
@@ -66,12 +70,11 @@ function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
VcsError | PlatformError.PlatformError,
VcsProcess.VcsProcess | FileSystem.FileSystem
> {
return Effect.gen(function* () {
const core = yield* GitCore;
yield* core.initRepo({ cwd });
yield* git(cwd, ["init"]);
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
@@ -14,8 +14,8 @@ import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
@@ -24,10 +24,26 @@ const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitCore;
const vcsRegistry = yield* VcsDriverRegistry;
const vcs = {
execute: (input: {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}) =>
vcsRegistry
.resolve({ cwd: input.cwd, requestedKind: "git" })
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
};
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
const resolveHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
@@ -36,7 +52,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -44,21 +60,18 @@ const makeCheckpointStore = Effect.gen(function* () {
}),
);
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
git
const hasHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.code === 0));
.pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (
cwd: string,
checkpointRef: CheckpointRef,
): Effect.Effect<string | null, GitCommandError> =>
git
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
vcs
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
@@ -67,7 +80,7 @@ const makeCheckpointStore = Effect.gen(function* () {
})
.pipe(
Effect.map((result) => {
if (result.code !== 0) {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
@@ -76,7 +89,7 @@ const makeCheckpointStore = Effect.gen(function* () {
);
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
git
vcs
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
@@ -84,7 +97,7 @@ const makeCheckpointStore = Effect.gen(function* () {
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
@@ -108,7 +121,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
@@ -116,14 +129,14 @@ const makeCheckpointStore = Effect.gen(function* () {
});
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
const writeTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
@@ -131,16 +144,17 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git write-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.execute({
const commitTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
@@ -148,15 +162,16 @@ const makeCheckpointStore = Effect.gen(function* () {
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
@@ -197,12 +212,12 @@ const makeCheckpointStore = Effect.gen(function* () {
return false;
}
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
@@ -210,7 +225,7 @@ const makeCheckpointStore = Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
@@ -235,15 +250,16 @@ const makeCheckpointStore = Effect.gen(function* () {
}
if (!fromCommitOid || !toCommitOid) {
return yield* new GitCommandError({
return yield* new VcsProcessExitError({
operation,
command: "git diff",
cwd: input.cwd,
exitCode: 1,
detail: "Checkpoint ref is unavailable for diff operation.",
});
}
const result = yield* git.execute({
const result = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
@@ -262,7 +278,7 @@ const makeCheckpointStore = Effect.gen(function* () {
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
@@ -14,23 +14,25 @@ import type {
} from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "../Services/GitManager.ts";
import { type GitManagerShape } from "./GitManager.ts";
import {
type GitHubCliShape,
type GitHubPullRequestSummary,
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
} from "../sourceControl/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../textGeneration/TextGeneration.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceControlProvider.ts";
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerConfig } from "../config.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
ProjectSetupScriptRunner,
type ProjectSetupScriptRunnerInput,
type ProjectSetupScriptRunnerShape,
} from "../../project/Services/ProjectSetupScriptRunner.ts";
} from "../project/Services/ProjectSetupScriptRunner.ts";
interface FakeGhScenario {
prListSequence?: string[];
@@ -209,18 +211,27 @@ function runGit(
args: readonly string[],
allowNonZeroExit = false,
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
{
readonly exitCode: GitVcsDriver.ExecuteGitResult["exitCode"];
readonly stdout: string;
readonly stderr: string;
},
GitCommandError,
GitCore
GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
return yield* gitCore.execute({
const git = yield* GitVcsDriver.GitVcsDriver;
const result = yield* git.execute({
operation: "GitManager.test.runGit",
cwd,
args,
allowNonZeroExit,
});
return {
exitCode: result.exitCode,
stdout: result.stdout,
stderr: result.stderr,
};
});
}
@@ -229,7 +240,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -245,7 +256,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitVcsDriver.GitVcsDriver
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -259,7 +270,7 @@ function configureRemote(
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<void, GitCommandError, GitCore> {
): Effect.Effect<void, GitCommandError, GitVcsDriver.GitVcsDriver> {
return Effect.gen(function* () {
yield* runGit(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
yield* runGit(cwd, [
@@ -639,13 +650,25 @@ function makeManager(input?: {
const serverSettingsLayer = ServerSettingsService.layerTest();
const gitCoreLayer = GitCoreLive.pipe(
const vcsDriverLayer = GitVcsDriver.layer.pipe(
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
const sourceControlRegistryLayer = Layer.effect(
SourceControlProviderRegistry.SourceControlProviderRegistry,
GitHubSourceControlProvider.make().pipe(
Effect.map((provider) =>
SourceControlProviderRegistry.SourceControlProviderRegistry.of({
resolveHandle: () => Effect.succeed({ provider, context: null }),
resolve: () => Effect.succeed(provider),
}),
),
Effect.provide(Layer.succeed(GitHubCli, gitHubCli)),
),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
Layer.succeed(
ProjectSetupScriptRunner,
@@ -653,9 +676,9 @@ function makeManager(input?: {
runForThread: () => Effect.succeed({ status: "no-script" as const }),
},
),
gitCoreLayer,
vcsDriverLayer,
serverSettingsLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
).pipe(Layer.provideMerge(sourceControlRegistryLayer), Layer.provideMerge(NodeServices.layer));
return makeGitManager().pipe(
Effect.provide(managerLayer),
@@ -665,8 +688,9 @@ function makeManager(input?: {
const asThreadId = (threadId: string) => threadId as ThreadId;
const GitManagerTestLayer = GitCoreLive.pipe(
const GitManagerTestLayer = GitVcsDriver.layer.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
);
@@ -698,15 +722,15 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const status = yield* manager.status({ cwd: repoDir });
expect(status.isRepo).toBe(true);
expect(status.hasOriginRemote).toBe(true);
expect(status.isDefaultBranch).toBe(false);
expect(status.branch).toBe("feature/status-open-pr");
expect(status.hasPrimaryRemote).toBe(true);
expect(status.isDefaultRef).toBe(false);
expect(status.refName).toBe("feature/status-open-pr");
expect(status.pr).toEqual({
number: 13,
title: "Existing PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/13",
baseBranch: "main",
headBranch: "feature/status-open-pr",
baseRef: "main",
headRef: "feature/status-open-pr",
state: "open",
});
}),
@@ -743,8 +767,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 14,
title: "Existing PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
baseBranch: "main",
headBranch: "feature/status-trimmed-pr",
baseRef: "main",
headRef: "feature/status-trimmed-pr",
state: "open",
});
}),
@@ -794,8 +818,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 15,
title: "Valid PR title",
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
baseBranch: "main",
headBranch: "feature/status-valid-pr-entry",
baseRef: "main",
headRef: "feature/status-valid-pr-entry",
state: "open",
});
}),
@@ -843,8 +867,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
number: 17,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
baseBranch: "main",
headBranch: "feature/status-lowercase-state",
baseRef: "main",
headRef: "feature/status-lowercase-state",
state: "merged",
});
}),
@@ -859,9 +883,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -888,9 +912,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(status).toEqual({
isRepo: false,
hasOriginRemote: false,
isDefaultBranch: false,
branch: null,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -972,7 +996,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("main");
expect(status.refName).toBe("main");
expect(status.pr).toBeNull();
}),
);
@@ -1026,13 +1050,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("t3code/pr-488/statemachine");
expect(status.refName).toBe("t3code/pr-488/statemachine");
expect(status.pr).toEqual({
number: 488,
title: "Rebase this PR on latest main",
url: "https://github.com/pingdotgg/codething-mvp/pull/488",
baseBranch: "main",
headBranch: "statemachine",
baseRef: "main",
headRef: "statemachine",
state: "open",
});
expect(ghCalls).toContain(
@@ -1126,13 +1150,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("upstream/effect-atom");
expect(status.refName).toBe("upstream/effect-atom");
expect(status.pr).toEqual({
number: 1618,
title: "Correct PR",
url: "https://github.com/pingdotgg/t3code/pull/1618",
baseBranch: "main",
headBranch: "effect-atom",
baseRef: "main",
headRef: "effect-atom",
state: "open",
});
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
@@ -1176,13 +1200,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-merged-pr");
expect(status.refName).toBe("feature/status-merged-pr");
expect(status.pr).toEqual({
number: 22,
title: "Merged PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/22",
baseBranch: "main",
headBranch: "feature/status-merged-pr",
baseRef: "main",
headRef: "feature/status-merged-pr",
state: "merged",
});
}),
@@ -1213,7 +1237,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("main");
expect(status.refName).toBe("main");
expect(status.pr).toBeNull();
}),
);
@@ -1253,13 +1277,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-open-over-merged");
expect(status.refName).toBe("feature/status-open-over-merged");
expect(status.pr).toEqual({
number: 46,
title: "Open PR",
url: "https://github.com/pingdotgg/codething-mvp/pull/46",
baseBranch: "main",
headBranch: "feature/status-open-over-merged",
baseRef: "main",
headRef: "feature/status-open-over-merged",
state: "open",
});
}),
@@ -1284,7 +1308,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.branch).toBe("feature/status-no-gh");
expect(status.refName).toBe("feature/status-no-gh");
expect(status.pr).toBeNull();
}),
);
@@ -1708,6 +1732,49 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("create_pr falls back to main when source control provider detection fails", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/provider-fallback"]);
fs.writeFileSync(path.join(repoDir, "provider-fallback.txt"), "fallback\n");
yield* runGit(repoDir, ["add", "provider-fallback.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Provider fallback"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 404,
title: "Provider fallback",
url: "https://github.com/pingdotgg/codething-mvp/pull/404",
baseRefName: "main",
headRefName: "feature/provider-fallback",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "create_pr",
});
expect(result.pr.status).toBe("created");
expect(result.pr.number).toBe(404);
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/provider-fallback"),
),
).toBe(true);
}),
);
it.effect("returns existing PR metadata for commit/push/pr action", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -2989,6 +3056,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "hook_finished",
hookName: "pre-commit",
exitCode: 0,
}),
expect.objectContaining({
kind: "action_finished",
@@ -3119,7 +3187,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect.objectContaining({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
label: "Creating pull request...",
}),
]);
}),
@@ -2,29 +2,39 @@ import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import {
Array as Arr,
Cache,
Context,
DateTime,
Duration,
Effect,
Exit,
FileSystem,
Layer,
Option,
Order,
Path,
Ref,
Result,
} from "effect";
import {
GitActionProgressEvent,
GitActionProgressPhase,
GitCommandError,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
type GitStatusLocalResult,
type GitStatusRemoteResult,
VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
VcsStatusResult,
ModelSelection,
} from "@t3tools/contracts";
import {
detectGitHostingProviderFromRemoteUrl,
detectSourceControlProviderFromGitRemoteUrl,
mergeGitStatusParts,
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
@@ -32,24 +42,52 @@ import {
} from "@t3tools/shared/git";
import { GitManagerError } from "@t3tools/contracts";
import {
GitManager,
type GitActionProgressReporter,
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import type { GitStatusDetails } from "../Services/GitCore.ts";
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
import { ProjectSetupScriptRunner } from "../project/Services/ProjectSetupScriptRunner.ts";
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
import {
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
import { GitVcsDriver, type GitStatusDetails } from "../vcs/GitVcsDriver.ts";
import { SourceControlProviderRegistry } from "../sourceControl/SourceControlProviderRegistry.ts";
import type { ChangeRequest } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
export interface GitManagerShape {
readonly status: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly localStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
"t3/git/GitManager",
) {}
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
@@ -75,9 +113,14 @@ interface OpenPrInfo {
interface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {
state: "open" | "closed" | "merged";
updatedAt: string | null;
updatedAt: Option.Option<DateTime.Utc>;
}
const pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(
Order.flip(Option.makeOrder(DateTime.Order)),
(pullRequest) => pullRequest.updatedAt,
);
interface ResolvedPullRequest {
number: number;
title: string;
@@ -88,9 +131,9 @@ interface ResolvedPullRequest {
}
interface PullRequestHeadRemoteInfo {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
}
interface BranchHeadContext {
@@ -256,7 +299,7 @@ function matchesBranchHeadContext(
return true;
}
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
function toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {
return {
number: summary.number,
title: summary.title,
@@ -264,7 +307,7 @@ function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state ?? "open",
updatedAt: null,
updatedAt: summary.updatedAt,
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
@@ -422,16 +465,16 @@ function toStatusPr(pr: PullRequestInfo): {
number: number;
title: string;
url: string;
baseBranch: string;
headBranch: string;
baseRef: string;
headRef: string;
state: "open" | "closed" | "merged";
} {
return {
number: pr.number,
title: pr.title,
url: pr.url,
baseBranch: pr.baseRefName,
headBranch: pr.headRefName,
baseRef: pr.baseRefName,
headRef: pr.headRefName,
state: pr.state,
};
}
@@ -475,9 +518,9 @@ function shouldPreferSshRemote(url: string | null): boolean {
}
function toPullRequestHeadRemoteInfo(pr: {
isCrossRepository?: boolean;
headRepositoryNameWithOwner?: string | null;
headRepositoryOwnerLogin?: string | null;
isCrossRepository?: boolean | undefined;
headRepositoryNameWithOwner?: string | null | undefined;
headRepositoryOwnerLogin?: string | null | undefined;
}): PullRequestHeadRemoteInfo {
return {
...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),
@@ -491,10 +534,12 @@ function toPullRequestHeadRemoteInfo(pr: {
}
export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const gitCore = yield* GitCore;
const gitHubCli = yield* GitHubCli;
const gitCore = yield* GitVcsDriver;
const sourceControlProviders = yield* SourceControlProviderRegistry;
const textGeneration = yield* TextGeneration;
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner;
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
const serverSettingsService = yield* ServerSettingsService;
const createProgressEmitter = (
@@ -531,7 +576,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -586,7 +631,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return;
}
const cloneUrls = yield* gitHubCli.getRepositoryCloneUrls({
const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({
cwd,
repository: repositoryNameWithOwner,
});
@@ -659,14 +704,15 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
: null;
return {
kind: details.isRepo ? ("git" as const) : ("unknown" as const),
isRepo: details.isRepo,
...(hostingProvider ? { hostingProvider } : {}),
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),
hasPrimaryRemote: details.hasOriginRemote,
isDefaultRef: details.isDefaultBranch,
refName: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
} satisfies GitStatusLocalResult;
} satisfies VcsStatusLocalResult;
});
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
@@ -704,7 +750,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
aheadCount: details.aheadCount,
behindCount: details.behindCount,
pr,
} satisfies GitStatusRemoteResult;
} satisfies VcsStatusRemoteResult;
});
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
capacity: STATUS_RESULT_CACHE_CAPACITY,
@@ -728,7 +774,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
(yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??
(yield* readConfigValueNullable(cwd, "remote.origin.url"));
return remoteUrl ? detectGitHostingProviderFromRemoteUrl(remoteUrl) : null;
return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;
});
const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* (
@@ -833,9 +879,10 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
>,
) {
for (const headSelector of headContext.headSelectors) {
const pullRequests = yield* gitHubCli.listOpenPullRequests({
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
cwd,
headSelector,
state: "open",
limit: 1,
});
const normalizedPullRequests = pullRequests.map(toPullRequestInfo);
@@ -851,7 +898,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
baseRefName: firstPullRequest.baseRefName,
headRefName: firstPullRequest.headRefName,
state: "open",
updatedAt: null,
updatedAt: Option.none(),
} satisfies PullRequestInfo;
}
}
@@ -867,46 +914,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const parsedByNumber = new Map<number, PullRequestInfo>();
for (const headSelector of headContext.headSelectors) {
const stdout = yield* gitHubCli
.execute({
cwd,
args: [
"pr",
"list",
"--head",
headSelector,
"--state",
"all",
"--limit",
"20",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
})
.pipe(Effect.map((result) => result.stdout));
const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({
cwd,
headSelector,
state: "all",
limit: 20,
});
const raw = stdout.trim();
if (raw.length === 0) {
continue;
}
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) => {
if (!Result.isSuccess(decoded)) {
return Effect.fail(
gitManagerError(
"findLatestPr",
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
decoded.failure,
),
);
}
return Effect.succeed(decoded.success);
}),
);
for (const pr of pullRequests) {
for (const pr of pullRequests.map(toPullRequestInfo)) {
if (!matchesBranchHeadContext(pr, headContext)) {
continue;
}
@@ -914,11 +929,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => {
const left = a.updatedAt ? Date.parse(a.updatedAt) : 0;
const right = b.updatedAt ? Date.parse(b.updatedAt) : 0;
return right - left;
});
const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);
const latestOpenPr = parsed.find((pr) => pr.state === "open");
if (latestOpenPr) {
@@ -1035,11 +1046,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
}
}
const defaultFromGh = yield* gitHubCli
.getDefaultBranch({ cwd })
.pipe(Effect.catch(() => Effect.succeed(null)));
if (defaultFromGh) {
return defaultFromGh;
const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(
Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),
Effect.catch(() => Effect.succeed(null)),
);
if (defaultFromProvider) {
return defaultFromProvider;
}
return "main";
@@ -1272,12 +1284,12 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
yield* emit({
kind: "phase_started",
phase: "pr",
label: "Creating GitHub pull request...",
label: "Creating pull request...",
});
yield* gitHubCli
.createPullRequest({
yield* (yield* sourceControlProvider(cwd))
.createChangeRequest({
cwd,
baseBranch,
baseRefName: baseBranch,
headSelector: headContext.preferredHeadSelector,
title: generated.title,
bodyFile,
@@ -1335,8 +1347,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")(
function* (input) {
const pullRequest = yield* gitHubCli
.getPullRequest({
const pullRequest = yield* (yield* sourceControlProvider(input.cwd))
.getChangeRequest({
cwd: input.cwd,
reference: normalizePullRequestReference(input.reference),
})
@@ -1370,14 +1382,14 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return yield* Effect.gen(function* () {
const normalizedReference = normalizePullRequestReference(input.reference);
const rootWorktreePath = canonicalizeExistingPath(input.cwd);
const pullRequestSummary = yield* gitHubCli.getPullRequest({
const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({
cwd: input.cwd,
reference: normalizedReference,
});
const pullRequest = toResolvedPullRequest(pullRequestSummary);
if (input.mode === "local") {
yield* gitHubCli.checkoutPullRequest({
yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({
cwd: input.cwd,
reference: normalizedReference,
force: true,
@@ -1420,9 +1432,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
const findLocalHeadBranch = (cwd: string) =>
gitCore.listBranches({ cwd }).pipe(
gitCore.listRefs({ cwd }).pipe(
Effect.map((result) => {
const localBranch = result.branches.find(
const localBranch = result.refs.find(
(branch) => !branch.isRemote && branch.name === localPullRequestBranch,
);
if (localBranch) {
@@ -1432,7 +1444,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return null;
}
return (
result.branches.find(
result.refs.find(
(branch) =>
!branch.isRemote &&
branch.name === pullRequest.headBranch &&
@@ -1495,7 +1507,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const worktree = yield* gitCore.createWorktree({
cwd: input.cwd,
branch: localPullRequestBranch,
refName: localPullRequestBranch,
path: null,
});
yield* ensureExistingWorktreeUpstream(worktree.worktree.path);
@@ -1503,7 +1515,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
return {
pullRequest,
branch: worktree.worktree.branch,
branch: worktree.worktree.refName,
worktreePath: worktree.worktree.path,
};
}).pipe(Effect.ensuring(invalidateStatus(input.cwd)));
@@ -1535,8 +1547,8 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
yield* gitCore.createRef({ cwd, refName: resolvedBranch });
yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));
return {
branchStep: { status: "created" as const, name: resolvedBranch },
@@ -1737,4 +1749,4 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
} satisfies GitManagerShape;
});
export const GitManagerLive = Layer.effect(GitManager, makeGitManager());
export const layer = Layer.effect(GitManager, makeGitManager());
+271
View File
@@ -0,0 +1,271 @@
import { Context, Effect, Layer } from "effect";
import {
GitManagerError,
GitCommandError,
type VcsDriverKind,
type VcsSwitchRefInput,
type VcsSwitchRefResult,
type VcsCreateRefInput,
type VcsCreateRefResult,
type VcsCreateWorktreeInput,
type VcsCreateWorktreeResult,
type VcsListRefsInput,
type VcsListRefsResult,
type GitManagerServiceError,
type GitPreparePullRequestThreadInput,
type GitPreparePullRequestThreadResult,
type GitPullRequestRefInput,
type VcsPullResult,
type VcsRemoveWorktreeInput,
type GitResolvePullRequestResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
type VcsStatusResult,
} from "@t3tools/contracts";
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
export interface GitWorkflowServiceShape {
readonly status: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly localStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly remoteStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
readonly createWorktree: (
input: VcsCreateWorktreeInput,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
readonly createRef: (
input: VcsCreateRefInput,
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
readonly switchRef: (
input: VcsSwitchRefInput,
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
readonly initRepo: (input: { readonly cwd: string }) => Effect.Effect<void, GitCommandError>;
readonly renameBranch: (input: {
readonly cwd: string;
readonly oldBranch: string;
readonly newBranch: string;
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
}
export class GitWorkflowService extends Context.Service<
GitWorkflowService,
GitWorkflowServiceShape
>()("t3/git/GitWorkflowService") {}
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
new GitManagerError({
operation,
detail: `${detail} (${cwd})`,
});
const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =>
new GitCommandError({
operation,
command: "vcs-route",
cwd,
detail,
});
const emptyWorkingTree = { files: [], insertions: 0, deletions: 0 } as const;
const nonGitLocalStatus = (kind: VcsDriverKind, isRepo: boolean): VcsStatusLocalResult => ({
kind,
isRepo,
hasPrimaryRemote: false,
isDefaultRef: false,
refName: null,
hasWorkingTreeChanges: false,
workingTree: emptyWorkingTree,
});
export const make = Effect.fn("makeGitWorkflowService")(function* () {
const registry = yield* VcsDriverRegistry;
const git = yield* GitVcsDriver;
const gitManager = yield* GitManager;
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitWorkflow(
operation,
cwd,
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
);
}
});
const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
operation: string,
cwd: string,
) {
const handle = yield* registry
.resolve({ cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitCommand(
operation,
cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle.kind !== "git") {
return yield* unsupportedGitCommand(
operation,
cwd,
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
);
}
});
const routeGitManager =
<Input extends { readonly cwd: string }, Output>(
operation: string,
run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
) =>
(input: Input) =>
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
const localStatus: GitWorkflowServiceShape["localStatus"] = Effect.fn(
"GitWorkflowService.localStatus",
)(function* (input) {
const handle = yield* registry
.detect({ cwd: input.cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
"GitWorkflowService.localStatus",
input.cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (!handle) {
return nonGitLocalStatus("unknown", false);
}
if (handle.kind === "git") {
return yield* gitManager.localStatus(input);
}
return nonGitLocalStatus(handle.kind, true);
});
const remoteStatus: GitWorkflowServiceShape["remoteStatus"] = Effect.fn(
"GitWorkflowService.remoteStatus",
)(function* (input) {
const handle = yield* registry
.detect({ cwd: input.cwd })
.pipe(
Effect.mapError((error) =>
unsupportedGitWorkflow(
"GitWorkflowService.remoteStatus",
input.cwd,
error instanceof Error ? error.message : String(error),
),
),
);
if (handle?.kind === "git") {
return yield* gitManager.remoteStatus(input);
}
return null;
});
const status: GitWorkflowServiceShape["status"] = Effect.fn("GitWorkflowService.status")(
function* (input) {
const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)]);
return mergeGitStatusParts(local, remote);
},
);
return GitWorkflowService.of({
status,
localStatus,
remoteStatus,
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
pullCurrentBranch: (cwd) =>
ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
Effect.andThen(git.pullCurrentBranch(cwd)),
),
runStackedAction: (input, options) =>
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
Effect.andThen(gitManager.runStackedAction(input, options)),
),
resolvePullRequest: routeGitManager(
"GitWorkflowService.resolvePullRequest",
gitManager.resolvePullRequest,
),
preparePullRequestThread: routeGitManager(
"GitWorkflowService.preparePullRequestThread",
gitManager.preparePullRequestThread,
),
listRefs: (input) =>
ensureGitCommand("GitWorkflowService.listRefs", input.cwd).pipe(
Effect.andThen(git.listRefs(input)),
),
createWorktree: (input) =>
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
Effect.andThen(git.createWorktree(input)),
),
removeWorktree: (input) =>
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
Effect.andThen(git.removeWorktree(input)),
),
createRef: (input) =>
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
Effect.andThen(git.createRef(input)),
),
switchRef: (input) =>
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
Effect.andThen(Effect.scoped(git.switchRef(input))),
),
initRepo: (input) => git.initRepo(input),
renameBranch: (input) =>
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
Effect.andThen(git.renameBranch(input)),
),
});
});
export const layer = Layer.effect(GitWorkflowService, make());
File diff suppressed because it is too large. Load diff
@@ -1,311 +0,0 @@
import { realpathSync } from "node:fs";
import {
Duration,
Effect,
Exit,
Fiber,
Layer,
PubSub,
Ref,
Scope,
Stream,
SynchronizedRef,
} from "effect";
import type {
GitStatusInput,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../Services/GitStatusBroadcaster.ts";
import { GitManager } from "../Services/GitManager.ts";
const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface GitStatusChange {
readonly cwd: string;
readonly event: GitStatusStreamEvent;
}
interface CachedValue<T> {
readonly fingerprint: string;
readonly value: T;
}
interface CachedGitStatus {
readonly local: CachedValue<GitStatusLocalResult> | null;
readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
}
interface ActiveRemotePoller {
readonly fiber: Fiber.Fiber<void, never>;
readonly subscriberCount: number;
}
function normalizeCwd(cwd: string): string {
try {
return realpathSync.native(cwd);
} catch {
return cwd;
}
}
function fingerprintStatusPart(status: unknown): string {
return JSON.stringify(status);
}
export const GitStatusBroadcasterLive = Layer.effect(
GitStatusBroadcaster,
Effect.gen(function* () {
const gitManager = yield* GitManager;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<GitStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
);
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
});
const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
cwd: string,
local: GitStatusLocalResult,
options?: { publish?: boolean },
) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<GitStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
});
}
return local;
});
const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
cwd: string,
remote: GitStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<GitStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
remote: nextRemote,
});
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "remoteUpdated",
remote,
},
});
}
return remote;
});
const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
const local = yield* gitManager.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.local) {
return cached.local.value;
}
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
});
const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
input: GitStatusInput,
) {
const normalizedCwd = normalizeCwd(input.cwd);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(normalizedCwd),
getOrLoadRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
});
const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
"refreshLocalStatus",
)(function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
yield* gitManager.invalidateLocalStatus(normalizedCwd);
const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
});
const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
yield* gitManager.invalidateRemoteStatus(cwd);
const remote = yield* gitManager.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
function* (cwd) {
const normalizedCwd = normalizeCwd(cwd);
const [local, remote] = yield* Effect.all([
refreshLocalStatus(normalizedCwd),
refreshRemoteStatus(normalizedCwd),
]);
return mergeGitStatusParts(local, remote);
},
);
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
Effect.logWarning("git remote status refresh failed", {
cwd,
detail: error.message,
});
return refreshRemoteStatus(cwd).pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
),
),
),
);
};
const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (existing) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount + 1,
});
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
subscriberCount: 1,
});
return [undefined, nextPollers] as const;
}),
);
});
});
const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (!existing) {
return [null, activePollers] as const;
}
if (existing.subscriberCount > 1) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount - 1,
});
return [null, nextPollers] as const;
}
const nextPollers = new Map(activePollers);
nextPollers.delete(cwd);
return [existing.fiber, nextPollers] as const;
});
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
}
});
const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const normalizedCwd = normalizeCwd(input.cwd);
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
yield* retainRemotePoller(normalizedCwd);
const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
local: initialLocal,
remote: initialRemote,
}),
Stream.fromSubscription(subscription).pipe(
Stream.filter((event) => event.cwd === normalizedCwd),
Stream.map((event) => event.event),
),
).pipe(Stream.ensuring(release));
}),
);
return {
getStatus,
refreshLocalStatus,
refreshStatus,
streamStatus,
} satisfies GitStatusBroadcasterShape;
}),
);
@@ -1,101 +0,0 @@
/**
* TextGenerationLive — registry-backed implementation of the `TextGeneration`
* service tag.
*
* The `TextGeneration` tag is kept as a thin facade over
* `ProviderInstanceRegistry`. Every op pulls `modelSelection.instanceId`,
* looks up the matching `ProviderInstance`, and delegates to that instance's
* own `textGeneration` closure (built by its driver's `create()`).
*
* There is deliberately no per-driver dispatch here — the registry already
* knows which driver backs each instance, and each `ProviderInstance`
* carries the fully-bound `TextGenerationShape` produced by its driver.
* That means:
*
* - Multiple instances of the same driver (e.g. `codex_personal`,
* `codex_work`) each get their own text-generation closure bound to
* their own settings — the routing is by instance, not by driver.
* - Unknown or disabled instances surface a `TextGenerationError` with
* the missing `instanceId`, instead of silently falling back to a
* default.
*
* This replaces the old `RoutingTextGenerationLive`, which tried to route
* by driver-kind and misused `modelSelection.instanceId` as a driver-id
* literal.
*
* @module git/Layers/TextGenerationLive
*/
import { Effect, Layer } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import type { ProviderInstanceId } from "@t3tools/contracts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
import { TextGeneration, type TextGenerationShape } from "../Services/TextGeneration.ts";
type TextGenerationOp =
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
const resolveInstance = (
registry: ProviderInstanceRegistryShape,
operation: TextGenerationOp,
instanceId: ProviderInstanceId,
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance
? Effect.succeed(instance.textGeneration)
: Effect.fail(
new TextGenerationError({
operation,
detail: `No provider instance registered for id '${instanceId}'.`,
}),
),
),
);
/**
* Build a `TextGenerationShape` that routes every call through the
* registry. Exposed separately from the Layer so tests can construct it
* against a stub registry without layering gymnastics.
*/
export const makeTextGenerationFromRegistry = (
registry: ProviderInstanceRegistryShape,
): TextGenerationShape => ({
generateCommitMessage: (input) =>
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateCommitMessage(input)),
),
generatePrContent: (input) =>
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generatePrContent(input)),
),
generateBranchName: (input) =>
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateBranchName(input)),
),
generateThreadTitle: (input) =>
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
Effect.flatMap((tg) => tg.generateThreadTitle(input)),
),
});
/**
* `TextGeneration` Layer wired to the `ProviderInstanceRegistry`. The rest
* of the server keeps using `yield* TextGeneration` — only the underlying
* wiring changed from kind-based routing to instance-based routing.
*/
export const TextGenerationLive = Layer.effect(
TextGeneration,
Effect.gen(function* () {
const registry = yield* ProviderInstanceRegistry;
return makeTextGenerationFromRegistry(registry);
}),
);
-313
View File
@@ -1,313 +0,0 @@
/**
* GitCore - Effect service contract for low-level Git operations.
*
* Wraps core repository primitives used by higher-level orchestration
* services and WebSocket routes.
*
* @module GitCore
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type {
GitCheckoutInput,
GitCheckoutResult,
GitCreateBranchInput,
GitCreateBranchResult,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
GitInitInput,
GitListBranchesInput,
GitListBranchesResult,
GitPullResult,
GitRemoveWorktreeInput,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
import type { GitCommandError } from "@t3tools/contracts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
upstreamBranch?: string | undefined;
setUpstream?: boolean | undefined;
}
export interface GitRangeContext {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface GitListWorkspaceFilesResult {
readonly paths: ReadonlyArray<string>;
readonly truncated: boolean;
}
export interface GitRenameBranchInput {
cwd: string;
oldBranch: string;
newBranch: string;
}
export interface GitRenameBranchResult {
branch: string;
}
export interface GitFetchPullRequestBranchInput {
cwd: string;
prNumber: number;
branch: string;
}
export interface GitEnsureRemoteInput {
cwd: string;
preferredName: string;
url: string;
}
export interface GitFetchRemoteBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
localBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
remoteName: string;
remoteBranch: string;
}
/**
* GitCoreShape - Service API for low-level Git repository interactions.
*/
export interface GitCoreShape {
/**
* Execute a raw Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
/**
* Read Git status for a repository.
*/
readonly status: (input: GitStatusInput) => Effect.Effect<GitStatusResult, GitCommandError>;
/**
* Read detailed working tree / branch status for a repository.
*/
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Read detailed working tree / branch status without refreshing remote tracking refs.
*/
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
/**
* Build staged change context for commit generation.
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
* Create a commit with provided subject/body.
*/
readonly commit: (
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
* Push current branch, setting upstream if needed.
*/
readonly pushCurrentBranch: (
cwd: string,
fallbackBranch: string | null,
) => Effect.Effect<GitPushResult, GitCommandError>;
/**
* Collect commit/diff context between base branch and current HEAD.
*/
readonly readRangeContext: (
cwd: string,
baseBranch: string,
) => Effect.Effect<GitRangeContext, GitCommandError>;
/**
* Read a Git config value from the local repository.
*/
readonly readConfigValue: (
cwd: string,
key: string,
) => Effect.Effect<string | null, GitCommandError>;
/**
* Determine whether the provided cwd is inside a git work tree.
*/
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
/**
* List tracked and untracked workspace file paths relative to cwd.
*/
readonly listWorkspaceFiles: (
cwd: string,
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
/**
* Remove gitignored paths from a relative path list.
*/
readonly filterIgnoredPaths: (
cwd: string,
relativePaths: ReadonlyArray<string>,
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
/**
* List local + remote branches and branch metadata.
*/
readonly listBranches: (
input: GitListBranchesInput,
) => Effect.Effect<GitListBranchesResult, GitCommandError>;
/**
* Pull current branch from upstream using fast-forward only.
*/
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<GitPullResult, GitCommandError>;
/**
* Create a worktree and branch from a base branch.
*/
readonly createWorktree: (
input: GitCreateWorktreeInput,
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
/**
* Materialize a GitHub pull request head as a local branch without switching checkout.
*/
readonly fetchPullRequestBranch: (
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Ensure a named remote exists for the provided URL, returning the reused or created remote name.
*/
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
/**
* Fetch a remote branch into a local branch without checkout.
*/
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Set the upstream tracking branch for a local branch.
*/
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Remove an existing worktree.
*/
readonly removeWorktree: (input: GitRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
/**
* Rename an existing local branch.
*/
readonly renameBranch: (
input: GitRenameBranchInput,
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
/**
* Create a local branch.
*/
readonly createBranch: (
input: GitCreateBranchInput,
) => Effect.Effect<GitCreateBranchResult, GitCommandError>;
/**
* Checkout an existing branch and refresh its upstream metadata in background.
*/
readonly checkoutBranch: (
input: GitCheckoutInput,
) => Effect.Effect<GitCheckoutResult, GitCommandError>;
/**
* Initialize a repository in the provided directory.
*/
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
/**
* List local branch names (short format).
*/
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
}
/**
* GitCore - Service tag for low-level Git repository operations.
*/
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
-103
View File
@@ -1,103 +0,0 @@
/**
* GitHubCli - Effect service contract for `gh` process interactions.
*
* Provides thin command execution helpers used by Git workflow orchestration.
*
* @module GitHubCli
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner.ts";
import type { GitHubCliError } from "@t3tools/contracts";
export interface GitHubPullRequestSummary {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitHubRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
/**
* GitHubCliShape - Service API for executing GitHub CLI commands.
*/
export interface GitHubCliShape {
/**
* Execute a GitHub CLI command and return full process output.
*/
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
/**
* List open pull requests for a head branch.
*/
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
/**
* Resolve a pull request by URL, number, or branch-ish identifier.
*/
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
/**
* Resolve clone URLs for a GitHub repository.
*/
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
/**
* Create a pull request from branch context and body file.
*/
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
/**
* Resolve repository default branch through GitHub metadata.
*/
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>;
/**
* Checkout a pull request into the current repository worktree.
*/
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitHubCliError>;
}
/**
* GitHubCli - Service tag for GitHub CLI process execution.
*/
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
"t3/git/Services/GitHubCli",
) {}
-104
View File
@@ -1,104 +0,0 @@
/**
* GitManager - Effect service contract for stacked Git workflows.
*
* Orchestrates status inspection and commit/push/PR flows by composing
* lower-level Git and external tool services.
*
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusInput,
GitStatusResult,
} from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
/**
* GitManagerShape - Service API for high-level Git workflow actions.
*/
export interface GitManagerShape {
/**
* Read current repository Git status plus open PR metadata when available.
*/
readonly status: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Read local repository status without remote hosting enrichment.
*/
readonly localStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
/**
* Read remote tracking / PR status for a repository.
*/
readonly remoteStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusRemoteResult | null, GitManagerServiceError>;
/**
* Clear any cached local status snapshot for a repository.
*/
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached remote status snapshot for a repository.
*/
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Clear any cached status snapshot for a repository so the next read is fresh.
*/
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
/**
* Prepare a new thread workspace from a pull request in local or worktree mode.
*/
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
/**
* GitManager - Service tag for stacked Git workflow orchestration.
*/
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
"t3/git/Services/GitManager",
) {}
@@ -1,27 +0,0 @@
import { Context } from "effect";
import type { Effect, Stream } from "effect";
import type {
GitManagerServiceError,
GitStatusInput,
GitStatusLocalResult,
GitStatusResult,
GitStatusStreamEvent,
} from "@t3tools/contracts";
export interface GitStatusBroadcasterShape {
readonly getStatus: (
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly refreshLocalStatus: (
cwd: string,
) => Effect.Effect<GitStatusLocalResult, GitManagerServiceError>;
readonly refreshStatus: (cwd: string) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: GitStatusInput,
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
}
export class GitStatusBroadcaster extends Context.Service<
GitStatusBroadcaster,
GitStatusBroadcasterShape
>()("t3/git/Services/GitStatusBroadcaster") {}
-165
View File
@@ -1,171 +1,6 @@
/**
* Shared utilities for text generation layers (Codex, Claude, etc.).
*
* @module textGenerationUtils
*/
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
+4 -5
View File
@@ -1,4 +1,4 @@
import { Cause, Exit, Result, Schema } from "effect";
import { Cause, DateTime, Exit, Option, Result, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
@@ -9,7 +9,7 @@ export interface NormalizedGitHubPullRequestRecord {
readonly baseRefName: string;
readonly headRefName: string;
readonly state: "open" | "closed" | "merged";
readonly updatedAt: string | null;
readonly updatedAt: Option.Option<DateTime.Utc>;
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
@@ -23,7 +23,7 @@ const GitHubPullRequestSchema = Schema.Struct({
headRefName: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),
isCrossRepository: Schema.optional(Schema.Boolean),
headRepository: Schema.optional(
Schema.NullOr(
@@ -80,8 +80,7 @@ function normalizeGitHubPullRequestRecord(
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
state: normalizeGitHubPullRequestState(raw),
updatedAt:
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
updatedAt: raw.updatedAt ?? Option.none(),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
@@ -24,8 +24,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
@@ -282,7 +283,7 @@ describe("CheckpointReactor", () => {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-reactor-test-",
});
const gitStatusBroadcasterLayer = Layer.succeed(GitStatusBroadcaster, {
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: (cwd: string) =>
Effect.sync(() => {
@@ -290,9 +291,10 @@ describe("CheckpointReactor", () => {
}).pipe(
Effect.as({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -305,11 +307,16 @@ describe("CheckpointReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(gitStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer))),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(VcsDriverRegistry.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -24,7 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import type { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
type ReactorInput =
@@ -70,7 +70,7 @@ const make = Effect.gen(function* () {
const checkpointStore = yield* CheckpointStore;
const receiptBus = yield* RuntimeReceiptBus;
const workspaceEntries = yield* WorkspaceEntries;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const appendRevertFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -508,7 +508,7 @@ const make = Effect.gen(function* () {
return;
}
yield* gitStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to refresh local git status after turn completion", {
threadId: event.threadId,
@@ -33,12 +33,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "../../git/Services/GitStatusBroadcaster.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -52,6 +47,8 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService, type GitWorkflowServiceShape } from "../../git/GitWorkflowService.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
@@ -243,9 +240,10 @@ describe("ProviderCommandReactor", () => {
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "renamed-branch",
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "renamed-branch",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -324,15 +322,19 @@ describe("ProviderCommandReactor", () => {
const layer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)),
Layer.provideMerge(
Layer.succeed(GitStatusBroadcaster, {
Layer.mock(GitWorkflowService)({
renameBranch,
} satisfies Partial<GitWorkflowServiceShape>),
),
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.die("refreshLocalStatus should not be called in this test"),
refreshStatus,
streamStatus: () => Stream.die("streamStatus should not be called in this test"),
} satisfies GitStatusBroadcasterShape),
}),
),
Layer.provideMerge(
Layer.mock(TextGeneration, {
@@ -16,12 +16,10 @@ import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream }
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
@@ -29,6 +27,8 @@ import {
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -168,8 +168,8 @@ function buildGeneratedWorktreeBranchName(raw: string): string {
const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const handledTurnStartKeys = yield* Cache.make<string, true>({
@@ -587,7 +587,7 @@ const make = Effect.gen(function* () {
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return;
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
@@ -595,7 +595,7 @@ const make = Effect.gen(function* () {
branch: renamed.branch,
worktreePath: cwd,
});
yield* gitStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
@@ -1,6 +1,9 @@
import type { RepositoryIdentity } from "@t3tools/contracts";
import { Cache, Duration, Effect, Exit, Layer } from "effect";
import { detectGitHostingProviderFromRemoteUrl, normalizeGitRemoteUrl } from "@t3tools/shared/git";
import {
detectSourceControlProviderFromGitRemoteUrl,
normalizeGitRemoteUrl,
} from "@t3tools/shared/git";
import { runProcess } from "../../processRunner.ts";
import {
@@ -45,7 +48,7 @@ function buildRepositoryIdentity(input: {
readonly rootPath: string;
}): RepositoryIdentity {
const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
const hostingProvider = detectGitHostingProviderFromRemoteUrl(input.remoteUrl);
const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
const repositoryPath = canonicalKey.split("/").slice(1).join("/");
const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
const [owner] = repositoryPathSegments;
@@ -60,7 +63,7 @@ function buildRepositoryIdentity(input: {
},
rootPath: input.rootPath,
...(repositoryPath ? { displayName: repositoryPath } : {}),
...(hostingProvider ? { provider: hostingProvider.kind } : {}),
...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
...(owner ? { owner } : {}),
...(repositoryName ? { name: repositoryName } : {}),
};
@@ -16,7 +16,7 @@ import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tool
import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeClaudeTextGeneration } from "../../git/Layers/ClaudeTextGeneration.ts";
import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
@@ -25,7 +25,7 @@ import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeCodexTextGeneration } from "../../git/Layers/CodexTextGeneration.ts";
import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCodexAdapter } from "../Layers/CodexAdapter.ts";
@@ -17,7 +17,7 @@ import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { makeCursorTextGeneration } from "../../git/Layers/CursorTextGeneration.ts";
import { makeCursorTextGeneration } from "../../textGeneration/CursorTextGeneration.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeCursorAdapter } from "../Layers/CursorAdapter.ts";
import {
@@ -16,7 +16,7 @@ import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3to
import { Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { makeOpenCodeTextGeneration } from "../../git/Layers/OpenCodeTextGeneration.ts";
import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
import { ServerConfig } from "../../config.ts";
import { ProviderDriverError } from "../Errors.ts";
import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
@@ -14,7 +14,7 @@ import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../ProviderDriver.ts";
import type { TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
+1 -1
View File
@@ -28,7 +28,7 @@ import type {
} from "@t3tools/contracts";
import type { Effect, Schema, Scope } from "effect";
import type { TextGenerationShape } from "../git/Services/TextGeneration.ts";
import type { TextGenerationShape } from "../textGeneration/TextGeneration.ts";
import type { ProviderAdapterError, ProviderDriverError } from "./Errors.ts";
import type { ProviderAdapterShape } from "./Services/ProviderAdapter.ts";
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
+236 -124
View File
@@ -29,6 +29,7 @@ import { assert, it } from "@effect/vitest";
import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
import {
Deferred,
DateTime,
Duration,
Effect,
FileSystem,
@@ -38,6 +39,7 @@ import {
Path,
Stream,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
FetchHttpClient,
HttpBody,
@@ -50,6 +52,8 @@ import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
import { vi } from "vitest";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
import type { ServerConfigShape } from "./config.ts";
import { deriveServerPaths, ServerConfig } from "./config.ts";
import { makeRoutesLayer } from "./server.ts";
@@ -58,13 +62,7 @@ import {
CheckpointDiffQuery,
type CheckpointDiffQueryShape,
} from "./checkpointing/Services/CheckpointDiffQuery.ts";
import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts";
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
import {
GitStatusBroadcaster,
type GitStatusBroadcasterShape,
} from "./git/Services/GitStatusBroadcaster.ts";
import { GitManager, type GitManagerShape } from "./git/GitManager.ts";
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
import { Open, type OpenShape } from "./open.ts";
import {
@@ -105,6 +103,19 @@ import {
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import type { VcsDriverShape } from "./vcs/VcsDriver.ts";
import {
VcsStatusBroadcaster,
type VcsStatusBroadcasterShape,
layer as VcsStatusBroadcasterLayer,
} from "./vcs/VcsStatusBroadcaster.ts";
import {
VcsDriverRegistry,
type VcsDriverRegistryShape,
type VcsDriverHandle,
} from "./vcs/VcsDriverRegistry.ts";
import { layer as GitWorkflowServiceLayer } from "./git/GitWorkflowService.ts";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
@@ -195,16 +206,6 @@ const makeDefaultOrchestrationThreadShell = (
};
};
const workspaceAndProjectServicesLayer = Layer.mergeAll(
WorkspacePathsLive,
WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive)),
WorkspaceFileSystemLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provide(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
),
ProjectFaviconResolverLive,
);
const browserOtlpTracingLayer = Layer.mergeAll(
FetchHttpClient.layer,
OtlpSerialization.layerJson,
@@ -324,9 +325,11 @@ const buildAppUnderTest = (options?: {
providerRegistry?: Partial<ProviderRegistryShape>;
serverSettings?: Partial<ServerSettingsShape>;
open?: Partial<OpenShape>;
gitCore?: Partial<GitCoreShape>;
vcsDriver?: Partial<VcsDriverShape>;
vcsDriverRegistry?: Partial<VcsDriverRegistryShape>;
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
gitManager?: Partial<GitManagerShape>;
gitStatusBroadcaster?: Partial<GitStatusBroadcasterShape>;
vcsStatusBroadcaster?: Partial<VcsStatusBroadcasterShape>;
projectSetupScriptRunner?: Partial<ProjectSetupScriptRunnerShape>;
terminalManager?: Partial<TerminalManagerShape>;
orchestrationEngine?: Partial<OrchestrationEngineShape>;
@@ -372,22 +375,108 @@ const buildAppUnderTest = (options?: {
...options?.config,
};
const layerConfig = Layer.succeed(ServerConfig, config);
const gitCoreLayer = Layer.mock(GitCore)({
const defaultVcsDriver: VcsDriverShape = {
capabilities: {
kind: "git",
supportsWorktrees: true,
supportsBookmarks: false,
supportsAtomicSnapshot: false,
supportsPushDefaultRemote: true,
ignoreClassifier: "native",
},
execute: () =>
Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}),
detectRepository: () => Effect.succeed(null),
isInsideWorkTree: () => Effect.succeed(false),
listWorkspaceFiles: () =>
Effect.succeed({
paths: [],
truncated: false,
freshness: {
source: "live-local",
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
}),
listRemotes: () =>
Effect.succeed({
remotes: [],
freshness: {
source: "live-local",
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
}),
filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths),
...options?.layers?.gitCore,
...options?.layers?.vcsDriver,
};
const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry)({
detect: (input) =>
defaultVcsDriver.detectRepository(input.cwd).pipe(
Effect.flatMap((repository) =>
repository
? Effect.succeed(repository)
: defaultVcsDriver.isInsideWorkTree(input.cwd).pipe(
Effect.map((isInsideWorkTree) =>
isInsideWorkTree
? {
kind: "git" as const,
rootPath: input.cwd,
metadataPath: null,
freshness: {
source: "live-local" as const,
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
}
: null,
),
),
),
Effect.map((repository) =>
repository
? ({
kind: repository.kind,
repository,
driver: defaultVcsDriver,
} satisfies VcsDriverHandle)
: null,
),
),
resolve: (input) =>
Effect.succeed({
kind:
input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind,
repository: {
kind:
input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind,
rootPath: input.cwd,
metadataPath: null,
freshness: {
source: "live-local",
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
},
driver: defaultVcsDriver,
}),
...options?.layers?.vcsDriverRegistry,
});
const gitVcsDriverLayer = Layer.mock(GitVcsDriver.GitVcsDriver)({
...options?.layers?.gitVcsDriver,
});
const gitManagerLayer = Layer.mock(GitManager)({
...options?.layers?.gitManager,
});
const workspaceEntriesLayer = WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(vcsDriverRegistryLayer),
);
const workspaceAndProjectServicesLayer = Layer.mergeAll(
WorkspacePathsLive,
@@ -398,11 +487,16 @@ const buildAppUnderTest = (options?: {
),
ProjectFaviconResolverLive,
);
const gitStatusBroadcasterLayer = options?.layers?.gitStatusBroadcaster
? Layer.mock(GitStatusBroadcaster)({
...options.layers.gitStatusBroadcaster,
const gitWorkflowLayer = GitWorkflowServiceLayer.pipe(
Layer.provideMerge(vcsDriverRegistryLayer),
Layer.provideMerge(gitVcsDriverLayer),
Layer.provideMerge(gitManagerLayer),
);
const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster
? Layer.mock(VcsStatusBroadcaster)({
...options.layers.vcsStatusBroadcaster,
})
: GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer));
: VcsStatusBroadcasterLayer.pipe(Layer.provide(gitWorkflowLayer));
const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, {
disableListenLog: true,
@@ -441,9 +535,10 @@ const buildAppUnderTest = (options?: {
...options?.layers?.open,
}),
),
Layer.provide(gitCoreLayer),
Layer.provide(gitManagerLayer),
Layer.provideMerge(gitStatusBroadcasterLayer),
Layer.provide(gitVcsDriverLayer),
Layer.provide(gitWorkflowLayer),
Layer.provideMerge(vcsStatusBroadcasterLayer),
Layer.provide(
Layer.mock(ProjectSetupScriptRunner)({
runForThread: () => Effect.succeed({ status: "no-script" as const }),
@@ -2068,12 +2163,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitCore: {
vcsDriver: {
isInsideWorkTree: () => Effect.succeed(true),
listWorkspaceFiles: () =>
Effect.succeed({
paths: ["src/tracked.ts"],
truncated: false,
freshness: {
source: "live-local",
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
}),
filterIgnoredPaths: (_cwd, relativePaths) =>
Effect.succeed(
@@ -2273,9 +2373,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -2289,9 +2390,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
status: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
@@ -2372,16 +2474,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
worktreePath: null,
}),
},
gitCore: {
gitVcsDriver: {
pullCurrentBranch: () =>
Effect.succeed({
status: "pulled",
branch: "main",
upstreamBranch: "origin/main",
refName: "main",
upstreamRef: "origin/main",
}),
listBranches: () =>
listRefs: () =>
Effect.succeed({
branches: [
refs: [
{
name: "main",
current: true,
@@ -2390,17 +2492,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
],
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 1,
}),
createWorktree: () =>
Effect.succeed({
worktree: { path: "/tmp/wt", branch: "feature/demo" },
worktree: { path: "/tmp/wt", refName: "feature/demo" },
}),
removeWorktree: () => Effect.void,
createBranch: (input) => Effect.succeed({ branch: input.branch }),
checkoutBranch: (input) => Effect.succeed({ branch: input.branch }),
createRef: (input) => Effect.succeed({ refName: input.refName }),
switchRef: (input) => Effect.succeed({ refName: input.refName }),
initRepo: () => Effect.void,
},
},
@@ -2409,13 +2511,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const wsUrl = yield* getWsServerUrl("/ws");
const pull = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })),
);
assert.equal(pull.status, "pulled");
const refreshedStatus = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitRefreshStatus]({ cwd: "/tmp/repo" }),
client[WS_METHODS.vcsRefreshStatus]({ cwd: "/tmp/repo" }),
),
);
assert.equal(refreshedStatus.isRepo, true);
@@ -2459,27 +2561,25 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.equal(prepared.branch, "feature/demo");
const branches = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitListBranches]({ cwd: "/tmp/repo" }),
),
const refs = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsListRefs]({ cwd: "/tmp/repo" })),
);
assert.equal(branches.branches[0]?.name, "main");
assert.equal(refs.refs[0]?.name, "main");
const worktree = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitCreateWorktree]({
client[WS_METHODS.vcsCreateWorktree]({
cwd: "/tmp/repo",
branch: "main",
refName: "main",
path: null,
}),
),
);
assert.equal(worktree.worktree.branch, "feature/demo");
assert.equal(worktree.worktree.refName, "feature/demo");
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitRemoveWorktree]({
client[WS_METHODS.vcsRemoveWorktree]({
cwd: "/tmp/repo",
path: "/tmp/wt",
}),
@@ -2488,25 +2588,25 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitCreateBranch]({
client[WS_METHODS.vcsCreateRef]({
cwd: "/tmp/repo",
branch: "feature/new",
refName: "feature/new",
}),
),
);
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitCheckout]({
client[WS_METHODS.vcsSwitchRef]({
cwd: "/tmp/repo",
branch: "main",
refName: "main",
}),
),
);
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[WS_METHODS.gitInit]({
client[WS_METHODS.vcsInit]({
cwd: "/tmp/repo",
}),
),
@@ -2526,7 +2626,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
let statusCalls = 0;
yield* buildAppUnderTest({
layers: {
gitCore: {
gitVcsDriver: {
pullCurrentBranch: () => Effect.fail(gitError),
},
gitManager: {
@@ -2545,9 +2645,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -2566,9 +2667,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
statusCalls += 1;
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
@@ -2583,7 +2685,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const wsUrl = yield* getWsServerUrl("/ws");
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })).pipe(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })).pipe(
Effect.result,
),
);
@@ -2622,9 +2724,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -2643,9 +2746,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
statusCalls += 1;
return {
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
hasWorkingTreeChanges: true,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
@@ -2680,12 +2784,12 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.gen(function* () {
yield* buildAppUnderTest({
layers: {
gitCore: {
gitVcsDriver: {
pullCurrentBranch: () =>
Effect.succeed({
status: "pulled" as const,
branch: "main",
upstreamBranch: "origin/main",
refName: "main",
upstreamRef: "origin/main",
}),
},
gitManager: {
@@ -2694,9 +2798,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: true,
branch: "main",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -2716,7 +2821,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const wsUrl = yield* getWsServerUrl("/ws");
const startedAt = Date.now();
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.gitPull]({ cwd: "/tmp/repo" })),
withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })),
);
const elapsedMs = Date.now() - startedAt;
@@ -2737,9 +2842,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
localStatus: () =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
kind: "git",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -2813,9 +2919,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
Effect.andThen(
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
@@ -3479,9 +3586,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
const refreshStatus = vi.fn((_: string) =>
Effect.succeed({
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "t3code/bootstrap-branch",
kind: "git" as const,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "t3code/bootstrap-refName",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -3494,13 +3602,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
pr: null,
}),
);
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
branch: "t3code/bootstrap-branch",
path: "/tmp/bootstrap-worktree",
},
}),
const createWorktree = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
refName: "t3code/bootstrap-refName",
path: "/tmp/bootstrap-worktree",
},
}),
);
const runForThread = vi.fn(
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
@@ -3515,10 +3624,10 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitCore: {
gitVcsDriver: {
createWorktree,
},
gitStatusBroadcaster: {
vcsStatusBroadcaster: {
refreshStatus,
},
orchestrationEngine: {
@@ -3566,7 +3675,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
branch: "t3code/bootstrap-refName",
},
runSetupScript: true,
},
@@ -3588,8 +3697,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
cwd: "/tmp/project",
branch: "main",
newBranch: "t3code/bootstrap-branch",
refName: "main",
newRefName: "t3code/bootstrap-refName",
path: null,
});
assert.deepEqual(runForThread.mock.calls[0]?.[0], {
@@ -3619,13 +3728,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
branch: "t3code/bootstrap-branch",
path: "/tmp/bootstrap-worktree",
},
}),
const createWorktree = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
refName: "t3code/bootstrap-refName",
path: "/tmp/bootstrap-worktree",
},
}),
);
const runForThread = vi.fn(
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
@@ -3634,7 +3744,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitCore: {
gitVcsDriver: {
createWorktree,
},
orchestrationEngine: {
@@ -3682,7 +3792,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
branch: "t3code/bootstrap-refName",
},
runSetupScript: true,
},
@@ -3712,13 +3822,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
branch: "t3code/bootstrap-branch",
path: "/tmp/bootstrap-worktree",
},
}),
const createWorktree = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
refName: "t3code/bootstrap-refName",
path: "/tmp/bootstrap-worktree",
},
}),
);
const runForThread = vi.fn(
(_: Parameters<ProjectSetupScriptRunnerShape["runForThread"]>[0]) =>
@@ -3734,7 +3845,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitCore: {
gitVcsDriver: {
createWorktree,
},
orchestrationEngine: {
@@ -3798,7 +3909,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
branch: "t3code/bootstrap-refName",
},
runSetupScript: true,
},
@@ -3830,13 +3941,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
it.effect("cleans up created bootstrap threads when worktree creation defects", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
Effect.die(new Error("worktree exploded")),
const createWorktree = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriverShape["createWorktree"]>[0]) =>
Effect.die(new Error("worktree exploded")),
);
yield* buildAppUnderTest({
layers: {
gitCore: {
gitVcsDriver: {
createWorktree,
},
orchestrationEngine: {
@@ -3881,7 +3993,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-branch",
branch: "t3code/bootstrap-refName",
},
runSetupScript: false,
},
+47 -18
View File
@@ -25,13 +25,11 @@ import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReap
import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
import { GitCoreLive } from "./git/Layers/GitCore.ts";
import { GitHubCliLive } from "./git/Layers/GitHubCli.ts";
import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts";
import { TextGenerationLive } from "./git/Layers/TextGenerationLive.ts";
import * as GitHubCli from "./sourceControl/GitHubCli.ts";
import * as TextGeneration from "./textGeneration/TextGeneration.ts";
import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
import { GitManagerLive } from "./git/Layers/GitManager.ts";
import * as GitManager from "./git/GitManager.ts";
import { KeybindingsLive } from "./keybindings.ts";
import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup.ts";
import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";
@@ -47,6 +45,13 @@ import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdent
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
import * as VcsProcess from "./vcs/VcsProcess.ts";
import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
@@ -133,11 +138,6 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(RuntimeReceiptBusLive),
);
const CheckpointingLayerLive = Layer.empty.pipe(
Layer.provideMerge(CheckpointDiffQueryLive),
Layer.provideMerge(CheckpointStoreLive),
);
const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
@@ -155,24 +155,49 @@ const ProviderLayerLive = ProviderServiceLive.pipe(
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
const GitManagerLayerLive = GitManagerLive.pipe(
const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
Layer.provide(VcsProjectConfig.layer),
);
const GitManagerLayerLive = GitManager.layer.pipe(
Layer.provideMerge(ProjectSetupScriptRunnerLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(TextGenerationLive),
Layer.provideMerge(GitVcsDriver.layer),
Layer.provideMerge(
SourceControlProviderRegistry.layer.pipe(
Layer.provide(GitHubCli.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
),
),
Layer.provideMerge(TextGeneration.layer),
);
const GitLayerLive = Layer.empty.pipe(
Layer.provideMerge(GitManagerLayerLive),
Layer.provideMerge(GitStatusBroadcasterLive.pipe(Layer.provide(GitManagerLayerLive))),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitVcsDriver.layer),
);
const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
Layer.provideMerge(VcsDriverRegistryLayerLive),
Layer.provideMerge(GitLayerLive),
);
const VcsLayerLive = Layer.empty.pipe(
Layer.provideMerge(VcsProjectConfig.layer),
Layer.provideMerge(VcsDriverRegistryLayerLive),
Layer.provideMerge(GitWorkflowLayerLive),
Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
);
const CheckpointingLayerLive = Layer.empty.pipe(
Layer.provideMerge(CheckpointDiffQueryLive),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
);
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(VcsDriverRegistryLayerLive),
);
const WorkspaceFileSystemLayerLive = WorkspaceFileSystemLive.pipe(
@@ -196,10 +221,11 @@ const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
Layer.provideMerge(OrchestrationLayerLive),
);
const RuntimeDependenciesLive = ReactorLayerLive.pipe(
const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
// Core Services
Layer.provideMerge(CheckpointingLayerLive),
Layer.provideMerge(GitLayerLive),
Layer.provideMerge(VcsLayerLive),
Layer.provideMerge(ProviderRuntimeLayerLive),
Layer.provideMerge(TerminalLayerLive),
Layer.provideMerge(PersistenceLayerLive),
@@ -229,7 +255,9 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerEnvironmentLive),
Layer.provideMerge(AuthLayerLive),
);
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
// Misc.
Layer.provideMerge(AnalyticsServiceLayerLive),
Layer.provideMerge(OpenLive),
@@ -310,6 +338,7 @@ export const makeServerLayer = Layer.unwrap(
Layer.provideMerge(HttpServerLive),
Layer.provide(ObservabilityLive),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(PlatformServicesLive),
);
}),
@@ -2,22 +2,21 @@ import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import { afterEach, expect, vi } from "vitest";
vi.mock("../../processRunner", () => ({
vi.mock("../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
import { runProcess } from "../processRunner.ts";
import * as GitHubCli from "./GitHubCli.ts";
const mockedRunProcess = vi.mocked(runProcess);
const layer = it.layer(GitHubCliLive);
const layer = it.layer(GitHubCli.layer);
afterEach(() => {
mockedRunProcess.mockReset();
});
layer("GitHubCliLive", (it) => {
layer("GitHubCli.layer", (it) => {
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
@@ -44,7 +43,7 @@ layer("GitHubCliLive", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
const gh = yield* GitHubCli.GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
@@ -102,7 +101,7 @@ layer("GitHubCliLive", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
const gh = yield* GitHubCli.GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
@@ -155,7 +154,7 @@ layer("GitHubCliLive", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
const gh = yield* GitHubCli.GitHubCli;
return yield* gh.listOpenPullRequests({
cwd: "/repo",
headSelector: "feature/pr-list",
@@ -190,7 +189,7 @@ layer("GitHubCliLive", (it) => {
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
const gh = yield* GitHubCli.GitHubCli;
return yield* gh.getRepositoryCloneUrls({
cwd: "/repo",
repository: "octocat/codething-mvp",
@@ -214,7 +213,7 @@ layer("GitHubCliLive", (it) => {
);
const error = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
const gh = yield* GitHubCli.GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "4888",
@@ -1,21 +1,81 @@
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { TrimmedNonEmptyString } from "@t3tools/contracts";
import { Context, Effect, Layer, Result, Schema, SchemaIssue } from "effect";
import { runProcess } from "../../processRunner.ts";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
type GitHubCliShape,
} from "../Services/GitHubCli.ts";
import { GitHubCliError, TrimmedNonEmptyString } from "@t3tools/contracts";
import type { ProcessRunResult } from "../processRunner.ts";
import { runProcess } from "../processRunner.ts";
import {
decodeGitHubPullRequestJson,
decodeGitHubPullRequestListJson,
formatGitHubJsonDecodeError,
} from "../githubPullRequests.ts";
} from "../git/githubPullRequests.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export interface GitHubPullRequestSummary {
readonly number: number;
readonly title: string;
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitHubRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
export interface GitHubCliShape {
readonly execute: (input: {
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly timeoutMs?: number;
}) => Effect.Effect<ProcessRunResult, GitHubCliError>;
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>;
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitHubCliError>;
}
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
"t3/source-control/GitHubCli",
) {}
function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown): GitHubCliError {
if (error instanceof Error) {
if (error.message.includes("Command not found: gh")) {
@@ -101,7 +161,7 @@ function decodeGitHubJson<S extends Schema.Top>(
);
}
const makeGitHubCli = Effect.sync(() => {
export const make = Effect.sync(() => {
const execute: GitHubCliShape["execute"] = (input) =>
Effect.tryPromise({
try: () =>
@@ -112,7 +172,7 @@ const makeGitHubCli = Effect.sync(() => {
catch: (error) => normalizeGitHubCliError("execute", error),
});
const service = {
return GitHubCli.of({
execute,
listOpenPullRequests: (input) =>
execute({
@@ -232,9 +292,7 @@ const makeGitHubCli = Effect.sync(() => {
cwd: input.cwd,
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
}).pipe(Effect.asVoid),
} satisfies GitHubCliShape;
return service;
});
});
export const GitHubCliLive = Layer.effect(GitHubCli, makeGitHubCli);
export const layer = Layer.effect(GitHubCli, make);
@@ -0,0 +1,152 @@
import { assert, it } from "@effect/vitest";
import { DateTime, Effect, Layer, Option } from "effect";
import { GitHubCli, type GitHubCliShape } from "./GitHubCli.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
const processResult = (stdout: string) => ({
stdout,
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
function makeProvider(github: Partial<GitHubCliShape>) {
return GitHubSourceControlProvider.make().pipe(Effect.provide(Layer.mock(GitHubCli)(github)));
}
it.effect("maps GitHub PR summaries into provider-neutral change requests", () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
getPullRequest: () =>
Effect.succeed({
number: 42,
title: "Add GitHub provider",
url: "https://github.com/pingdotgg/t3code/pull/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
}),
});
const changeRequest = yield* provider.getChangeRequest({
cwd: "/repo",
reference: "42",
});
assert.deepStrictEqual(changeRequest, {
provider: "github",
number: 42,
title: "Add GitHub provider",
url: "https://github.com/pingdotgg/t3code/pull/42",
baseRefName: "main",
headRefName: "feature/source-control",
state: "open",
updatedAt: Option.none(),
isCrossRepository: true,
headRepositoryNameWithOwner: "fork/t3code",
headRepositoryOwnerLogin: "fork",
});
}),
);
it.effect("uses gh json listing for non-open change request state queries", () =>
Effect.gen(function* () {
let executeArgs: ReadonlyArray<string> = [];
const provider = yield* makeProvider({
execute: (input) => {
executeArgs = input.args;
return Effect.succeed(
processResult(
JSON.stringify([
{
number: 7,
title: "Merged work",
url: "https://github.com/pingdotgg/t3code/pull/7",
baseRefName: "main",
headRefName: "feature/merged",
state: "merged",
updatedAt: "2026-01-02T00:00:00.000Z",
},
]),
),
);
},
});
const changeRequests = yield* provider.listChangeRequests({
cwd: "/repo",
headSelector: "feature/merged",
state: "all",
limit: 10,
});
assert.deepStrictEqual(executeArgs, [
"pr",
"list",
"--head",
"feature/merged",
"--state",
"all",
"--limit",
"10",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
]);
assert.strictEqual(changeRequests[0]?.provider, "github");
assert.strictEqual(changeRequests[0]?.state, "merged");
assert.deepStrictEqual(
changeRequests[0]?.updatedAt,
Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
);
}),
);
it.effect("treats empty non-open change request listing output as no results", () =>
Effect.gen(function* () {
const provider = yield* makeProvider({
execute: () => Effect.succeed(processResult("")),
});
const changeRequests = yield* provider.listChangeRequests({
cwd: "/repo",
headSelector: "feature/empty",
state: "all",
limit: 10,
});
assert.deepStrictEqual(changeRequests, []);
}),
);
it.effect("creates GitHub PRs through provider-neutral input names", () =>
Effect.gen(function* () {
let createInput: Parameters<GitHubCliShape["createPullRequest"]>[0] | null = null;
const provider = yield* makeProvider({
createPullRequest: (input) => {
createInput = input;
return Effect.void;
},
});
yield* provider.createChangeRequest({
cwd: "/repo",
baseRefName: "main",
headSelector: "owner:feature/provider",
title: "Provider PR",
bodyFile: "/tmp/body.md",
});
assert.deepStrictEqual(createInput, {
cwd: "/repo",
baseBranch: "main",
headSelector: "owner:feature/provider",
title: "Provider PR",
bodyFile: "/tmp/body.md",
});
}),
);
@@ -0,0 +1,145 @@
import { Effect, Layer, Option, Result, Schema } from "effect";
import {
SourceControlProviderError,
type ChangeRequest,
type ChangeRequestState,
type GitHubCliError,
} from "@t3tools/contracts";
import { GitHubCli, type GitHubPullRequestSummary } from "./GitHubCli.ts";
import { decodeGitHubPullRequestListJson } from "../git/githubPullRequests.ts";
import { SourceControlProvider, type SourceControlProviderShape } from "./SourceControlProvider.ts";
function providerError(operation: string, cause: GitHubCliError): SourceControlProviderError {
return new SourceControlProviderError({
provider: "github",
operation,
detail: cause.detail,
cause,
});
}
function toChangeRequest(summary: GitHubPullRequestSummary): ChangeRequest {
return {
provider: "github",
number: summary.number,
title: summary.title,
url: summary.url,
baseRefName: summary.baseRefName,
headRefName: summary.headRefName,
state: summary.state ?? "open",
updatedAt: Option.none(),
...(summary.isCrossRepository !== undefined
? { isCrossRepository: summary.isCrossRepository }
: {}),
...(summary.headRepositoryNameWithOwner !== undefined
? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }
: {}),
...(summary.headRepositoryOwnerLogin !== undefined
? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }
: {}),
};
}
export const make = Effect.fn("makeGitHubSourceControlProvider")(function* () {
const github = yield* GitHubCli;
const listChangeRequests: SourceControlProviderShape["listChangeRequests"] = (input) => {
if (input.state === "open") {
return github
.listOpenPullRequests({
cwd: input.cwd,
headSelector: input.headSelector,
...(input.limit !== undefined ? { limit: input.limit } : {}),
})
.pipe(
Effect.map((items) => items.map(toChangeRequest)),
Effect.mapError((error) => providerError("listChangeRequests", error)),
);
}
const stateArg: ChangeRequestState | "all" = input.state;
return github
.execute({
cwd: input.cwd,
args: [
"pr",
"list",
"--head",
input.headSelector,
"--state",
stateArg,
"--limit",
String(input.limit ?? 20),
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
})
.pipe(
Effect.flatMap((result) => {
const raw = result.stdout.trim();
if (raw.length === 0) {
return Effect.succeed([]);
}
return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
Effect.flatMap((decoded) =>
Result.isSuccess(decoded)
? Effect.succeed(
decoded.success.map((item) => ({
...toChangeRequest(item),
updatedAt: item.updatedAt,
})),
)
: Effect.fail(
new SourceControlProviderError({
provider: "github",
operation: "listChangeRequests",
detail: "GitHub CLI returned invalid change request JSON.",
cause: decoded.failure,
}),
),
),
);
}),
Effect.mapError((error) =>
Schema.is(SourceControlProviderError)(error)
? error
: providerError("listChangeRequests", error),
),
);
};
return SourceControlProvider.of({
kind: "github",
listChangeRequests,
getChangeRequest: (input) =>
github.getPullRequest(input).pipe(
Effect.map(toChangeRequest),
Effect.mapError((error) => providerError("getChangeRequest", error)),
),
createChangeRequest: (input) =>
github
.createPullRequest({
cwd: input.cwd,
baseBranch: input.baseRefName,
headSelector: input.headSelector,
title: input.title,
bodyFile: input.bodyFile,
})
.pipe(Effect.mapError((error) => providerError("createChangeRequest", error))),
getRepositoryCloneUrls: (input) =>
github
.getRepositoryCloneUrls(input)
.pipe(Effect.mapError((error) => providerError("getRepositoryCloneUrls", error))),
getDefaultBranch: (input) =>
github
.getDefaultBranch(input)
.pipe(Effect.mapError((error) => providerError("getDefaultBranch", error))),
checkoutChangeRequest: (input) =>
github
.checkoutPullRequest(input)
.pipe(Effect.mapError((error) => providerError("checkoutChangeRequest", error))),
});
});
export const layer = Layer.effect(SourceControlProvider, make());
@@ -0,0 +1,68 @@
import { Context, Effect } from "effect";
import type {
ChangeRequest,
ChangeRequestState,
SourceControlProviderError,
SourceControlProviderInfo,
SourceControlProviderKind,
SourceControlRepositoryCloneUrls,
} from "@t3tools/contracts";
export interface SourceControlProviderContext {
readonly provider: SourceControlProviderInfo;
readonly remoteName: string;
readonly remoteUrl: string;
}
export interface SourceControlRefSelector {
readonly refName: string;
readonly owner?: string;
readonly repository?: string;
}
export interface SourceControlProviderShape {
readonly kind: SourceControlProviderKind;
readonly listChangeRequests: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly source?: SourceControlRefSelector;
readonly headSelector: string;
readonly state: ChangeRequestState | "all";
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<ChangeRequest>, SourceControlProviderError>;
readonly getChangeRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly reference: string;
}) => Effect.Effect<ChangeRequest, SourceControlProviderError>;
readonly createChangeRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly source?: SourceControlRefSelector;
readonly target?: SourceControlRefSelector;
readonly baseRefName: string;
readonly headSelector: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, SourceControlProviderError>;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly repository: string;
}) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;
readonly getDefaultBranch: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
}) => Effect.Effect<string | null, SourceControlProviderError>;
readonly checkoutChangeRequest: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, SourceControlProviderError>;
}
export class SourceControlProvider extends Context.Service<
SourceControlProvider,
SourceControlProviderShape
>()("t3/source-control/SourceControlProvider") {}
@@ -0,0 +1,101 @@
import { assert, it } from "@effect/vitest";
import { DateTime, Effect, Layer, Option } from "effect";
import { GitHubCli } from "./GitHubCli.ts";
import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
import type { VcsDriverShape } from "../vcs/VcsDriver.ts";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
function makeRegistry(input: {
readonly remotes: ReadonlyArray<{
readonly name: string;
readonly url: string;
}>;
}) {
const driver = {
listRemotes: () =>
Effect.succeed({
remotes: input.remotes.map((remote) => ({
...remote,
pushUrl: Option.none(),
isPrimary: remote.name === "origin",
})),
freshness: {
source: "live-local" as const,
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
}),
} satisfies Partial<VcsDriverShape>;
const registryLayer = Layer.mock(VcsDriverRegistry)({
resolve: () =>
Effect.succeed({
kind: "git",
repository: {
kind: "git",
rootPath: "/repo",
metadataPath: null,
freshness: {
source: "live-local" as const,
observedAt: TEST_EPOCH,
expiresAt: Option.none(),
},
},
driver: driver as unknown as VcsDriverShape,
}),
});
return SourceControlProviderRegistry.make().pipe(
Effect.provide(Layer.mergeAll(registryLayer, Layer.mock(GitHubCli)({}))),
);
}
it.effect("routes GitHub remotes to the GitHub provider", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:pingdotgg/t3code.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "github");
}),
);
it.effect(
"detects GitLab remotes and returns an unsupported provider until one is registered",
() =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "origin", url: "[email protected]:group/project.git" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "gitlab");
const error = yield* Effect.flip(
provider.listChangeRequests({
cwd: "/repo",
headSelector: "feature/source-control",
state: "open",
}),
);
assert.strictEqual(error.provider, "gitlab");
}),
);
it.effect("falls back to a non-origin remote when origin is not configured", () =>
Effect.gen(function* () {
const registry = yield* makeRegistry({
remotes: [{ name: "upstream", url: "https://dev.azure.com/acme/project/_git/repo" }],
});
const provider = yield* registry.resolve({ cwd: "/repo" });
assert.strictEqual(provider.kind, "azure-devops");
}),
);
@@ -0,0 +1,155 @@
import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
import { SourceControlProviderError } from "@t3tools/contracts";
import type { SourceControlProviderKind } from "@t3tools/contracts";
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
import {
SourceControlProvider,
type SourceControlProviderContext,
type SourceControlProviderShape,
} from "./SourceControlProvider.ts";
import * as GitHubSourceControlProvider from "./GitHubSourceControlProvider.ts";
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;
const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);
export interface SourceControlProviderRegistration {
readonly kind: SourceControlProviderKind;
readonly provider: SourceControlProviderShape;
}
export interface SourceControlProviderHandle {
readonly provider: SourceControlProviderShape;
readonly context: SourceControlProviderContext | null;
}
export interface SourceControlProviderRegistryShape {
readonly resolveHandle: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;
readonly resolve: (input: {
readonly cwd: string;
}) => Effect.Effect<SourceControlProviderShape, SourceControlProviderError>;
}
export class SourceControlProviderRegistry extends Context.Service<
SourceControlProviderRegistry,
SourceControlProviderRegistryShape
>()("t3/source-control/SourceControlProviderRegistry") {}
function unsupportedProvider(kind: SourceControlProviderKind): SourceControlProviderShape {
const unsupported = (operation: string) =>
Effect.fail(
new SourceControlProviderError({
provider: kind,
operation,
detail: `No ${kind} source control provider is registered.`,
}),
);
return SourceControlProvider.of({
kind,
listChangeRequests: () => unsupported("listChangeRequests"),
getChangeRequest: () => unsupported("getChangeRequest"),
createChangeRequest: () => unsupported("createChangeRequest"),
getRepositoryCloneUrls: () => unsupported("getRepositoryCloneUrls"),
getDefaultBranch: () => unsupported("getDefaultBranch"),
checkoutChangeRequest: () => unsupported("checkoutChangeRequest"),
});
}
function providerDetectionError(operation: string, cwd: string, cause: unknown) {
return new SourceControlProviderError({
provider: "unknown",
operation,
detail: `Failed to detect source control provider for ${cwd}.`,
cause,
});
}
function selectProviderContext(
remotes: ReadonlyArray<{
readonly name: string;
readonly url: string;
}>,
): SourceControlProviderContext | null {
const candidates = remotes
.map((remote) => {
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
return provider
? {
provider,
remoteName: remote.name,
remoteUrl: remote.url,
}
: null;
})
.filter((value): value is SourceControlProviderContext => value !== null);
return (
candidates.find((candidate) => candidate.remoteName === "origin") ??
candidates.find((candidate) => candidate.provider.kind !== "unknown") ??
candidates[0] ??
null
);
}
export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")(
function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {
const vcsRegistry = yield* VcsDriverRegistry;
const providers = new Map<SourceControlProviderKind, SourceControlProviderShape>(
registrations.map((registration) => [registration.kind, registration.provider]),
);
const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")(
function* (cwd: string) {
const handle = yield* vcsRegistry
.resolve({ cwd })
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
const remotes = yield* handle.driver
.listRemotes(cwd)
.pipe(Effect.mapError((error) => providerDetectionError("detectProvider", cwd, error)));
return selectProviderContext(remotes.remotes);
},
);
const providerContextCache = yield* Cache.makeWith<
string,
SourceControlProviderContext | null,
SourceControlProviderError
>(detectProviderContext, {
capacity: PROVIDER_DETECTION_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),
});
const resolveHandle: SourceControlProviderRegistryShape["resolveHandle"] = (input) =>
Cache.get(providerContextCache, input.cwd).pipe(
Effect.map((context) => {
const kind = context?.provider.kind ?? "unknown";
return {
provider: providers.get(kind) ?? unsupportedProvider(kind),
context,
} satisfies SourceControlProviderHandle;
}),
);
return SourceControlProviderRegistry.of({
resolveHandle,
resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),
});
},
);
export const make = Effect.fn("makeSourceControlProviderRegistry")(function* () {
const github = yield* GitHubSourceControlProvider.make();
return yield* makeWithProviders([
{
kind: "github",
provider: github,
},
]);
});
export const layer = Layer.effect(SourceControlProviderRegistry, make());
@@ -5,9 +5,9 @@ import { Effect, FileSystem, Layer, Path, Schema } from "effect";
import { createModelSelection } from "@t3tools/shared/model";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { sanitizeThreadTitle } from "./TextGenerationUtils.ts";
import { makeClaudeTextGeneration } from "./ClaudeTextGeneration.ts";
const ClaudeTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
@@ -184,7 +184,7 @@ function withFakeClaudeEnv<A, E, R>(
}).pipe(Effect.scoped);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
withFakeClaudeEnv(
{
@@ -14,20 +14,20 @@ import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
} from "./TextGenerationPrompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
@@ -37,8 +37,8 @@ import {
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "../../provider/Layers/ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../../provider/Drivers/ClaudeHome.ts";
} from "../provider/Layers/ClaudeProvider.ts";
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -6,8 +6,8 @@ import { expect } from "vitest";
import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
@@ -168,7 +168,7 @@ function withFakeCodexEnv<A, E, R>(
}).pipe(Effect.scoped);
}
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
{
@@ -4,28 +4,28 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { type CodexSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import { TextGenerationError } from "@t3tools/contracts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
} from "./TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
} from "./TextGenerationPrompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
@@ -386,7 +386,3 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
generateThreadTitle,
} satisfies TextGenerationShape;
});
// NOTE: `CodexTextGenerationLive` (the singleton Layer) has been removed.
// `makeCodexTextGeneration(codexConfig)` is now invoked directly by
// `CodexDriver.create()` for each configured instance.
@@ -11,12 +11,12 @@ import { expect } from "vitest";
import { CursorSettings, ProviderInstanceId } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
import { ServerConfig } from "../config.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeCursorTextGeneration } from "./CursorTextGeneration.ts";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const mockAgentPath = path.join(__dirname, "../../scripts/acp-mock-agent.ts");
function shellSingleQuote(value: string): string {
return `'${value.replaceAll("'", `'"'"'`)}'`;
@@ -82,7 +82,7 @@ function waitForFileContent(path: string): Effect.Effect<string> {
});
}
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => {
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
@@ -100,9 +100,9 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-text-generation",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
"diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
modelSelection: {
...createModelSelection(ProviderInstanceId.make("cursor"), "gpt-5.4", [
{ id: "reasoning", value: "xhigh" },
@@ -243,9 +243,9 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/cursor-runtime-close",
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
stagedSummary: "M apps/server/src/textGeneration/CursorTextGeneration.ts",
stagedPatch:
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
"diff --git a/apps/server/src/textGeneration/CursorTextGeneration.ts b/apps/server/src/textGeneration/CursorTextGeneration.ts",
modelSelection: {
instanceId: ProviderInstanceId.make("cursor"),
model: "composer-2",
@@ -5,26 +5,23 @@ import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import {
type ThreadTitleGenerationResult,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
} from "./TextGenerationPrompts.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
applyCursorAcpModelSelection,
makeCursorAcpRuntime,
} from "../../provider/acp/CursorAcpSupport.ts";
} from "../provider/acp/CursorAcpSupport.ts";
const CURSOR_TIMEOUT_MS = 180_000;
@@ -277,7 +274,3 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
generateThreadTitle,
} satisfies TextGenerationShape;
});
// NOTE: `CursorTextGenerationLive` (the singleton Layer) has been removed.
// `makeCursorTextGeneration(cursorConfig)` is now invoked directly by
// `CursorDriver.create()` so each provider instance owns its own closure.
@@ -6,13 +6,13 @@ import { TestClock } from "effect/testing";
import { NetService } from "@t3tools/shared/Net";
import { beforeEach, expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { ServerConfig } from "../config.ts";
import {
OpenCodeRuntime,
OpenCodeRuntimeError,
type OpenCodeRuntimeShape,
} from "../../provider/opencodeRuntime.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
} from "../provider/opencodeRuntime.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import { makeOpenCodeTextGeneration } from "./OpenCodeTextGeneration.ts";
const runtimeMock = {
@@ -158,7 +158,7 @@ const advanceIdleClock = Effect.gen(function* () {
yield* Effect.yieldNow;
});
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
Effect.gen(function* () {
@@ -306,7 +306,7 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) =>
});
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
"OpenCodeTextGenerationLive with configured server URL",
"OpenCodeTextGeneration with configured server URL",
(it) => {
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
@@ -10,21 +10,21 @@ import {
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import { ServerConfig } from "../../config.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { resolveAttachmentPath } from "../attachmentStore.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import { type TextGenerationShape } from "../Services/TextGeneration.ts";
} from "./TextGenerationPrompts.ts";
import { type TextGenerationShape } from "./TextGeneration.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
} from "../Utils.ts";
} from "./TextGenerationUtils.ts";
import {
OpenCodeRuntime,
type OpenCodeServerConnection,
@@ -32,7 +32,7 @@ import {
openCodeRuntimeErrorDetail,
parseOpenCodeModelSlug,
toOpenCodeFileParts,
} from "../../provider/opencodeRuntime.ts";
} from "../provider/opencodeRuntime.ts";
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
@@ -5,11 +5,11 @@ import { describe, expect } from "vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import type { ProviderInstance } from "../../provider/ProviderDriver.ts";
import type { ProviderInstanceRegistryShape } from "../../provider/Services/ProviderInstanceRegistry.ts";
import type { TextGenerationShape } from "../Services/TextGeneration.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
import type { ProviderInstanceRegistryShape } from "../provider/Services/ProviderInstanceRegistry.ts";
import type { TextGenerationShape } from "./TextGeneration.ts";
import { makeTextGenerationFromRegistry } from "./TextGenerationLive.ts";
import { makeTextGenerationFromRegistry } from "./TextGeneration.ts";
const makeStubTextGeneration = (overrides: Partial<TextGenerationShape>): TextGenerationShape => ({
generateCommitMessage: () =>
@@ -1,18 +1,13 @@
/**
* TextGeneration - Effect service contract for AI-generated Git content.
*
* Generates commit messages and pull request titles/bodies from repository
* context prepared by Git services.
*
* @module TextGeneration
*/
import { Context } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import { Context, Effect, Layer } from "effect";
import type { ChatAttachment, ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
import { TextGenerationError } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
import {
ProviderInstanceRegistry,
type ProviderInstanceRegistryShape,
} from "../provider/Services/ProviderInstanceRegistry.ts";
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
export interface CommitMessageGenerationInput {
@@ -119,5 +114,58 @@ export interface TextGenerationShape {
* TextGeneration - Service tag for commit and PR text generation.
*/
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
"t3/git/Services/TextGeneration",
"t3/text-generation/TextGeneration",
) {}
type TextGenerationOp =
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
const resolveInstance = (
registry: ProviderInstanceRegistryShape,
operation: TextGenerationOp,
instanceId: ProviderInstanceId,
): Effect.Effect<ProviderInstance["textGeneration"], TextGenerationError> =>
registry.getInstance(instanceId).pipe(
Effect.flatMap((instance) =>
instance
? Effect.succeed(instance.textGeneration)
: Effect.fail(
new TextGenerationError({
operation,
detail: `No provider instance registered for id '${instanceId}'.`,
}),
),
),
);
export const makeTextGenerationFromRegistry = (
registry: ProviderInstanceRegistryShape,
): TextGenerationShape => ({
generateCommitMessage: (input) =>
resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),
),
generatePrContent: (input) =>
resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),
),
generateBranchName: (input) =>
resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),
),
generateThreadTitle: (input) =>
resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe(
Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),
),
});
export const layer = Layer.effect(
TextGeneration,
Effect.gen(function* () {
const registry = yield* ProviderInstanceRegistry;
return makeTextGenerationFromRegistry(registry);
}),
);
@@ -0,0 +1,19 @@
import { Schema } from "effect";
export const TextGenerationPolicyKind = Schema.Literals([
"default",
"conventional_commits",
"repo_conventions",
"custom",
]);
export type TextGenerationPolicyKind = typeof TextGenerationPolicyKind.Type;
export const TextGenerationPolicy = Schema.Struct({
kind: TextGenerationPolicyKind,
commitInstructions: Schema.optional(Schema.String),
changeRequestInstructions: Schema.optional(Schema.String),
branchInstructions: Schema.optional(Schema.String),
threadTitleInstructions: Schema.optional(Schema.String),
inferRepositoryConventions: Schema.Boolean,
});
export type TextGenerationPolicy = typeof TextGenerationPolicy.Type;
@@ -0,0 +1,41 @@
import type { TextGenerationPolicy, TextGenerationPolicyKind } from "./TextGenerationPolicy.ts";
export const defaultTextGenerationPolicy: TextGenerationPolicy = {
kind: "default",
inferRepositoryConventions: false,
};
export const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = {
kind: "conventional_commits",
commitInstructions:
"Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff.",
changeRequestInstructions:
"Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.",
inferRepositoryConventions: false,
};
export const repositoryConventionsTextGenerationPolicy: TextGenerationPolicy = {
kind: "repo_conventions",
commitInstructions:
"Follow the repository's established commit message style when examples are available.",
changeRequestInstructions:
"Follow the repository's established change request title and body style when examples are available.",
inferRepositoryConventions: true,
};
export const customTextGenerationPolicy = (
overrides: Omit<Partial<TextGenerationPolicy>, "kind">,
): TextGenerationPolicy => ({
kind: "custom",
inferRepositoryConventions: false,
...overrides,
});
export const textGenerationPresets: Record<
Exclude<TextGenerationPolicyKind, "custom">,
TextGenerationPolicy
> = {
default: defaultTextGenerationPolicy,
conventional_commits: conventionalCommitsTextGenerationPolicy,
repo_conventions: repositoryConventionsTextGenerationPolicy,
};
@@ -5,8 +5,8 @@ import {
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./Prompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
} from "./TextGenerationPrompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./TextGenerationUtils.ts";
import { TextGenerationError } from "@t3tools/contracts";
describe("buildCommitMessagePrompt", () => {
@@ -9,7 +9,13 @@
import { Schema } from "effect";
import type { ChatAttachment } from "@t3tools/contracts";
import { limitSection } from "./Utils.ts";
import { limitSection } from "./TextGenerationUtils.ts";
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
function policyInstruction(instruction: string | undefined): ReadonlyArray<string> {
const trimmed = instruction?.trim();
return trimmed ? ["", "Additional instructions:", limitSection(trimmed, 4_000)] : [];
}
// ---------------------------------------------------------------------------
// Commit message
@@ -20,6 +26,7 @@ export interface CommitMessagePromptInput {
stagedSummary: string;
stagedPatch: string;
includeBranch: boolean;
policy?: TextGenerationPolicy | undefined;
}
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
@@ -37,6 +44,7 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
...policyInstruction(input.policy?.commitInstructions),
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
@@ -77,6 +85,7 @@ export interface PrContentPromptInput {
commitSummary: string;
diffSummary: string;
diffPatch: string;
policy?: TextGenerationPolicy | undefined;
}
export function buildPrContentPrompt(input: PrContentPromptInput) {
@@ -88,6 +97,7 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
...policyInstruction(input.policy?.changeRequestInstructions),
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
@@ -117,6 +127,7 @@ export function buildPrContentPrompt(input: PrContentPromptInput) {
export interface BranchNamePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
policy?: TextGenerationPolicy | undefined;
}
interface PromptFromMessageInput {
@@ -125,6 +136,7 @@ interface PromptFromMessageInput {
rules: ReadonlyArray<string>;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
additionalInstructions?: string | undefined;
}
function buildPromptFromMessage(input: PromptFromMessageInput): string {
@@ -140,6 +152,7 @@ function buildPromptFromMessage(input: PromptFromMessageInput): string {
"",
"User message:",
limitSection(input.message, 8_000),
...policyInstruction(input.additionalInstructions),
];
if (attachmentLines.length > 0) {
promptSections.push(
@@ -164,6 +177,7 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
],
message: input.message,
attachments: input.attachments,
additionalInstructions: input.policy?.branchInstructions,
});
const outputSchema = Schema.Struct({
branch: Schema.String,
@@ -179,6 +193,7 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) {
export interface ThreadTitlePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
policy?: TextGenerationPolicy | undefined;
}
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
@@ -193,6 +208,7 @@ export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
],
message: input.message,
attachments: input.attachments,
additionalInstructions: input.policy?.threadTitleInstructions,
});
const outputSchema = Schema.Struct({
title: Schema.String,
@@ -0,0 +1,159 @@
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
export function extractJsonObject(raw: string): string {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return trimmed;
}
const start = trimmed.indexOf("{");
if (start < 0) {
return trimmed;
}
let depth = 0;
let inString = false;
let escaping = false;
for (let index = start; index < trimmed.length; index += 1) {
const char = trimmed[index];
if (inString) {
if (escaping) {
escaping = false;
} else if (char === "\\") {
escaping = true;
} else if (char === '"') {
inString = false;
}
continue;
}
if (char === '"') {
inString = true;
continue;
}
if (char === "{") {
depth += 1;
continue;
}
if (char === "}") {
depth -= 1;
if (depth === 0) {
return trimmed.slice(start, index + 1);
}
}
}
return trimmed.slice(start);
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
+99
View File
@@ -0,0 +1,99 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { assert, it } from "@effect/vitest";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import * as VcsProcess from "./VcsProcess.ts";
import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-git-vcs-contract-",
});
const GitContractLayer = Layer.mergeAll(GitVcsDriver.vcsLayer, GitVcsDriver.layer).pipe(
Layer.provide(ServerConfigLayer),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(NodeServices.layer),
);
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.execute({
operation: "GitVcsDriver.contract.git",
cwd,
args,
timeoutMs: 10_000,
});
});
type GitContractError = GitCommandError | PlatformError.PlatformError;
runVcsDriverContractSuite<GitVcsDriver.GitVcsDriver, GitContractError>({
name: "Git",
kind: "git",
layer: GitContractLayer,
fixture: {
createRepo: (cwd) =>
Effect.gen(function* () {
yield* runGit(cwd, ["init"]);
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
yield* runGit(cwd, ["config", "user.name", "Test"]);
}),
writeFile: (cwd, relativePath, contents) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const absolutePath = path.join(cwd, relativePath);
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
yield* fileSystem.writeFileString(absolutePath, contents);
}),
trackFile: (cwd, relativePath) => runGit(cwd, ["add", relativePath]),
commit: (cwd, message) => runGit(cwd, ["commit", "-m", message]),
ignorePath: (cwd, pattern) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
}),
},
});
it.effect("GitVcsDriver forwards execute env to the VCS process", () => {
let observedEnv: NodeJS.ProcessEnv | undefined;
return Effect.gen(function* () {
const driver = yield* GitVcsDriver.makeVcsDriverShape();
yield* driver.execute({
operation: "GitVcsDriver.test.env",
cwd: "/repo",
args: ["status"],
env: {
GIT_INDEX_FILE: "/tmp/t3-index",
},
});
assert.deepStrictEqual(observedEnv, {
GIT_INDEX_FILE: "/tmp/t3-index",
});
}).pipe(
Effect.provide(
Layer.mock(VcsProcess.VcsProcess)({
run: (input) =>
Effect.sync(() => {
observedEnv = input.env;
return {
exitCode: ChildProcessSpawner.ExitCode(0),
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
};
}),
}),
),
);
});
+528
View File
@@ -0,0 +1,528 @@
import { Context, Effect, Layer, Option } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
GitCommandError,
VcsProcessExitError,
type VcsSwitchRefInput,
type VcsSwitchRefResult,
type VcsCreateRefInput,
type VcsCreateRefResult,
type VcsCreateWorktreeInput,
type VcsCreateWorktreeResult,
type VcsInitInput,
type VcsListRefsInput,
type VcsListRefsResult,
type VcsPullResult,
type VcsRemoveWorktreeInput,
type VcsStatusInput,
type VcsStatusResult,
} from "@t3tools/contracts";
import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
import { nowFreshness } from "./VcsFreshness.ts";
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly exitCode: ChildProcessSpawner.ExitCode;
readonly stdout: string;
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
export interface GitStatusDetails {
isRepo: boolean;
sourceControlProvider?: VcsStatusResult["sourceControlProvider"];
hasOriginRemote: boolean;
isDefaultBranch: boolean;
branch: string | null;
upstreamRef: string | null;
hasWorkingTreeChanges: boolean;
workingTree: VcsStatusResult["workingTree"];
hasUpstream: boolean;
aheadCount: number;
behindCount: number;
}
export interface GitPreparedCommitContext {
stagedSummary: string;
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
upstreamBranch?: string | undefined;
setUpstream?: boolean | undefined;
}
export interface GitRangeContext {
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export interface GitRenameBranchInput {
cwd: string;
oldBranch: string;
newBranch: string;
}
export interface GitRenameBranchResult {
branch: string;
}
export interface GitFetchPullRequestBranchInput {
cwd: string;
prNumber: number;
branch: string;
}
export interface GitEnsureRemoteInput {
cwd: string;
preferredName: string;
url: string;
}
export interface GitFetchRemoteBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
localBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
remoteName: string;
remoteBranch: string;
}
export interface GitVcsDriverShape {
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
readonly commit: (
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
readonly pushCurrentBranch: (
cwd: string,
fallbackBranch: string | null,
) => Effect.Effect<GitPushResult, GitCommandError>;
readonly readRangeContext: (
cwd: string,
baseRef: string,
) => Effect.Effect<GitRangeContext, GitCommandError>;
readonly readConfigValue: (
cwd: string,
key: string,
) => Effect.Effect<string | null, GitCommandError>;
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
readonly createWorktree: (
input: VcsCreateWorktreeInput,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
readonly fetchPullRequestBranch: (
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
readonly renameBranch: (
input: GitRenameBranchInput,
) => Effect.Effect<GitRenameBranchResult, GitCommandError>;
readonly createRef: (
input: VcsCreateRefInput,
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
readonly switchRef: (
input: VcsSwitchRefInput,
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
}
export class GitVcsDriver extends Context.Service<GitVcsDriver, GitVcsDriverShape>()(
"t3/vcs/GitVcsDriver",
) {}
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
"-c",
"core.fsmonitor=false",
"-c",
"core.untrackedCache=false",
] as const;
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
const parts = input.split("\0");
if (parts.length === 0) return [];
if (truncated && parts[parts.length - 1]?.length) {
parts.pop();
}
return parts.filter((value) => value.length > 0);
}
function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
const chunks: string[][] = [];
let chunk: string[] = [];
let chunkBytes = 0;
for (const relativePath of relativePaths) {
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
chunk.push(relativePath);
chunkBytes += relativePathBytes;
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
}
if (chunk.length > 0) {
chunks.push(chunk);
}
return chunks;
}
function parseGitRemoteVerboseOutput(
output: string,
): Map<string, { url?: string; pushUrl?: string }> {
const remotes = new Map<string, { url?: string; pushUrl?: string }>();
for (const line of output.split("\n")) {
const trimmed = line.trim();
if (trimmed.length === 0) {
continue;
}
const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
if (!match) {
continue;
}
const name = match[1];
const url = match[2];
const direction = match[3];
if (!name || !url || !direction) {
continue;
}
const remote = remotes.get(name) ?? {};
if (direction === "fetch") {
remote.url = url;
} else {
remote.pushUrl = url;
}
remotes.set(name, remote);
}
return remotes;
}
const gitCommand = (
process: VcsProcessShape,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
options?: {
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
},
) =>
process.run({
operation,
command: "git",
args,
cwd,
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
...(options?.env !== undefined ? { env: options.env } : {}),
...(options?.allowNonZeroExit !== undefined
? { allowNonZeroExit: options.allowNonZeroExit }
: {}),
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
...(options?.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
: {}),
});
export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () {
const process = yield* VcsProcess;
const capabilities = {
kind: "git" as const,
supportsWorktrees: true,
supportsBookmarks: false,
supportsAtomicSnapshot: false,
supportsPushDefaultRemote: true,
ignoreClassifier: "native" as const,
};
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
gitCommand(
process,
"GitVcsDriver.isInsideWorkTree",
cwd,
["rev-parse", "--is-inside-work-tree"],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 4_096,
},
).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"));
const execute: VcsDriverShape["execute"] = (input) =>
gitCommand(process, input.operation, input.cwd, input.args, {
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.env !== undefined ? { env: input.env } : {}),
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
...(input.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
: {}),
});
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
function* (cwd) {
if (!(yield* isInsideWorkTree(cwd))) {
return null;
}
const root = yield* gitCommand(process, "GitVcsDriver.detectRepository.root", cwd, [
"rev-parse",
"--show-toplevel",
]);
const gitCommonDir = yield* gitCommand(
process,
"GitVcsDriver.detectRepository.commonDir",
cwd,
["rev-parse", "--git-common-dir"],
).pipe(Effect.catch(() => Effect.succeed(null)));
return {
kind: "git" as const,
rootPath: root.stdout.trim(),
metadataPath: gitCommonDir?.stdout.trim() || null,
freshness: yield* nowFreshness(),
};
},
);
const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
gitCommand(
process,
"GitVcsDriver.listWorkspaceFiles",
cwd,
[
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
"ls-files",
"--cached",
"--others",
"--exclude-standard",
"-z",
],
{
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
},
).pipe(
Effect.flatMap((result) =>
result.exitCode === 0
? Effect.gen(function* () {
const freshness = yield* nowFreshness();
return {
paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
truncated: result.stdoutTruncated,
freshness,
};
})
: Effect.fail(
new VcsProcessExitError({
operation: "GitVcsDriver.listWorkspaceFiles",
command: "git ls-files",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git ls-files failed",
}),
),
),
);
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
const result = yield* gitCommand(process, "GitVcsDriver.listRemotes", cwd, ["remote", "-v"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
});
if (result.exitCode !== 0) {
return yield* new VcsProcessExitError({
operation: "GitVcsDriver.listRemotes",
command: "git remote -v",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git remote -v failed",
});
}
const parsed = parseGitRemoteVerboseOutput(result.stdout);
const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {
if (!remote.url) {
return [];
}
return [
{
name,
url: remote.url,
pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),
isPrimary: name === "origin",
},
];
});
return {
remotes,
freshness: yield* nowFreshness(),
};
});
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
function* (cwd, relativePaths) {
if (relativePaths.length === 0) {
return relativePaths;
}
const ignoredPaths = new Set<string>();
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
for (const chunk of chunks) {
const result = yield* gitCommand(
process,
"GitVcsDriver.filterIgnoredPaths",
cwd,
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
{
stdin: `${chunk.join("\0")}\0`,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
},
);
if (result.exitCode !== 0 && result.exitCode !== 1) {
return yield* new VcsProcessExitError({
operation: "GitVcsDriver.filterIgnoredPaths",
command: "git check-ignore",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git check-ignore failed",
});
}
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
ignoredPaths.add(ignoredPath);
}
}
if (ignoredPaths.size === 0) {
return relativePaths;
}
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
},
);
return {
capabilities,
execute,
detectRepository,
isInsideWorkTree,
listWorkspaceFiles,
listRemotes,
filterIgnoredPaths,
} satisfies VcsDriverShape;
});
export const makeVcsDriver = Effect.fn("makeGitVcsDriver")(function* () {
const driver = yield* makeVcsDriverShape();
return VcsDriver.of(driver);
});
export const make = Effect.fn("makeGitVcsDriverService")(function* () {
const git = yield* makeGitVcsDriverCore();
return GitVcsDriver.of(git);
});
export const vcsLayer = Layer.effect(VcsDriver, makeVcsDriver());
export const layer = Layer.effect(GitVcsDriver, make());
@@ -0,0 +1,246 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, PlatformError, Scope } from "effect";
import { describe } from "vitest";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-git-vcs-driver-test-",
});
const TestLayer = GitVcsDriver.layer.pipe(
Layer.provide(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
const makeTmpDir = (
prefix = "git-vcs-driver-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
const writeTextFile = (
cwd: string,
relativePath: string,
contents: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const filePath = pathService.join(cwd, relativePath);
yield* fileSystem.makeDirectory(pathService.dirname(filePath), { recursive: true });
yield* fileSystem.writeFileString(filePath, contents);
});
const git = (
cwd: string,
args: ReadonlyArray<string>,
env?: NodeJS.ProcessEnv,
): Effect.Effect<string, GitCommandError, GitVcsDriver.GitVcsDriver> =>
Effect.gen(function* () {
const driver = yield* GitVcsDriver.GitVcsDriver;
const result = yield* driver.execute({
operation: "GitVcsDriver.test.git",
cwd,
args,
...(env ? { env } : {}),
timeoutMs: 10_000,
});
return result.stdout.trim();
});
const initRepoWithCommit = (
cwd: string,
): Effect.Effect<
{ readonly initialBranch: string },
GitCommandError | PlatformError.PlatformError,
GitVcsDriver.GitVcsDriver | FileSystem.FileSystem | Path.Path
> =>
Effect.gen(function* () {
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.initRepo({ cwd });
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(cwd, "README.md", "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
const initialBranch = yield* git(cwd, ["branch", "--show-current"]);
return { initialBranch };
});
it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
describe("repository status", () => {
it.effect("reports non-repository directories without failing", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* GitVcsDriver.GitVcsDriver;
const refs = yield* driver.listRefs({ cwd });
assert.equal(refs.isRepo, false);
assert.deepStrictEqual(refs.refs, []);
}),
);
it.effect("reports refName and dirty state for a repository", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* writeTextFile(cwd, "feature.ts", "export const value = 1;\n");
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd);
assert.equal(status.isRepo, true);
assert.equal(status.branch, initialBranch);
assert.equal(status.hasWorkingTreeChanges, true);
assert.include(
status.workingTree.files.map((file) => file.path),
"feature.ts",
);
}),
);
});
describe("refName operations", () => {
it.effect("creates, checks out, renames, and lists refs", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.createRef({ cwd, refName: "feature/original" });
const switchRef = yield* driver.switchRef({ cwd, refName: "feature/original" });
assert.equal(switchRef.refName, "feature/original");
const renamed = yield* driver.renameBranch({
cwd,
oldBranch: "feature/original",
newBranch: "feature/renamed",
});
assert.equal(renamed.branch, "feature/renamed");
assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/renamed");
const refs = yield* driver.listRefs({ cwd });
assert.equal(
refs.refs.find((refName) => refName.name === "feature/renamed")?.current,
true,
);
}),
);
it.effect("returns the existing refName when rename source and target match", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
const current = yield* git(cwd, ["branch", "--show-current"]);
const result = yield* driver.renameBranch({
cwd,
oldBranch: current,
newBranch: current,
});
assert.equal(result.branch, current);
}),
);
});
describe("worktree operations", () => {
it.effect("creates and removes a worktree for a new refName", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(cwd);
const pathService = yield* Path.Path;
const worktreePath = pathService.join(
yield* makeTmpDir("git-worktrees-"),
"feature-worktree",
);
const driver = yield* GitVcsDriver.GitVcsDriver;
const created = yield* driver.createWorktree({
cwd,
path: worktreePath,
refName: initialBranch,
newRefName: "feature/worktree",
});
assert.equal(created.worktree.path, worktreePath);
assert.equal(created.worktree.refName, "feature/worktree");
assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "feature/worktree");
yield* driver.removeWorktree({ cwd, path: worktreePath });
const fileSystem = yield* FileSystem.FileSystem;
assert.equal(yield* fileSystem.exists(worktreePath), false);
}),
);
});
describe("commit context", () => {
it.effect("stages selected files and commits only those files", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* writeTextFile(cwd, "a.txt", "a\n");
yield* writeTextFile(cwd, "b.txt", "b\n");
const context = yield* driver.prepareCommitContext(cwd, ["a.txt"]);
assert.include(context?.stagedSummary ?? "", "a.txt");
assert.notInclude(context?.stagedSummary ?? "", "b.txt");
const commit = yield* driver.commit(cwd, "Add a", "");
assert.match(commit.commitSha, /^[a-f0-9]{40}$/);
assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "Add a");
const status = yield* git(cwd, ["status", "--porcelain"]);
assert.include(status, "?? b.txt");
assert.notInclude(status, "a.txt");
}),
);
});
describe("remote operations", () => {
it.effect("pushes with upstream setup and skips when already up to date", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-remote-");
yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* (yield* GitVcsDriver.GitVcsDriver).createRef({
cwd,
refName: "feature/push",
});
yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({
cwd,
refName: "feature/push",
});
yield* writeTextFile(cwd, "feature.txt", "feature\n");
yield* (yield* GitVcsDriver.GitVcsDriver).prepareCommitContext(cwd);
yield* (yield* GitVcsDriver.GitVcsDriver).commit(cwd, "Add feature", "");
const pushed = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null);
assert.deepInclude(pushed, {
status: "pushed",
branch: "feature/push",
setUpstream: true,
});
assert.equal(
yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]),
"origin/feature/push",
);
const skipped = yield* (yield* GitVcsDriver.GitVcsDriver).pushCurrentBranch(cwd, null);
assert.deepInclude(skipped, {
status: "skipped_up_to_date",
branch: "feature/push",
});
}),
);
});
});
File diff suppressed because it is too large. Load diff
+193
View File
@@ -0,0 +1,193 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { describe } from "vitest";
import type { VcsError } from "@t3tools/contracts";
import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts";
import { VcsProcess, layer as VcsProcessLayer } from "./VcsProcess.ts";
import * as JjVcsDriver from "./JjVcsDriver.ts";
import { runVcsDriverContractSuite } from "./testing/VcsDriverContractHarness.ts";
const JjContractLayer = JjVcsDriver.vcsLayer.pipe(
Layer.provideMerge(VcsProcessLayer),
Layer.provideMerge(NodeServices.layer),
);
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
calls.map((call) => [call.command].concat(call.args));
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(exitCode),
stdout,
stderr,
stdoutTruncated: false,
stderrTruncated: false,
});
const runJj = (cwd: string, args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const process = yield* VcsProcess;
yield* process.run({
operation: "JjVcsDriver.contract.jj",
command: "jj",
cwd,
args,
timeoutMs: 10_000,
});
});
type JjContractError = PlatformError.PlatformError | VcsError;
runVcsDriverContractSuite<VcsProcess, JjContractError>({
name: "JJ",
kind: "jj",
layer: JjContractLayer,
fixture: {
createRepo: (cwd) => runJj(cwd, ["git", "init", "--colocate"]),
writeFile: (cwd, relativePath, contents) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const absolutePath = path.join(cwd, relativePath);
yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true });
yield* fileSystem.writeFileString(absolutePath, contents);
}),
ignorePath: (cwd, pattern) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fileSystem.writeFileString(path.join(cwd, ".gitignore"), `${pattern}\n`);
}),
},
});
describe("JjVcsDriver", () => {
it.effect("detects repository identity with jj root", () => {
const calls: VcsProcessInput[] = [];
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
const identity = yield* driver.detectRepository("/repo/src");
assert.equal(identity?.kind, "jj");
assert.equal(identity?.rootPath, "/repo");
assert.equal(identity?.metadataPath, "/repo/.jj");
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
return processOutput("/repo\n");
}),
}),
NodeServices.layer,
),
),
);
});
it.effect("lists workspace files using jj file list", () => {
let observedInput: VcsProcessInput | null = null;
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
const result = yield* driver.listWorkspaceFiles("/repo");
assert.deepStrictEqual(result.paths, ["README.md", "src/index.ts"]);
assert.deepStrictEqual(observedInput?.args, ["--no-pager", "file", "list"]);
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
observedInput = input;
return processOutput("README.md\nsrc/index.ts\n");
}),
}),
NodeServices.layer,
),
),
);
});
it.effect("filters paths with the git ignore oracle", () => {
const calls: VcsProcessInput[] = [];
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
const result = yield* driver.filterIgnoredPaths("/repo", [
"keep.ts",
"debug.log",
"src/index.ts",
]);
assert.deepStrictEqual(result, ["keep.ts", "src/index.ts"]);
assert.equal(calls[0]?.command, "git");
assert.deepStrictEqual(calls[0]?.args.slice(-2), ["init", "--bare"]);
assert.equal(calls[1]?.command, "git");
assert.deepStrictEqual(calls[1]?.args.slice(-4), [
"check-ignore",
"--no-index",
"-z",
"--stdin",
]);
assert.equal(calls[1]?.stdin, "keep.ts\0debug.log\0src/index.ts\0");
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
if (input.command === "git" && input.args.includes("check-ignore")) {
return processOutput("debug.log\0");
}
return processOutput("");
}),
}),
NodeServices.layer,
),
),
);
});
it.effect("forwards execute env to the VCS process", () => {
let observedEnv: NodeJS.ProcessEnv | undefined;
return Effect.gen(function* () {
const driver = yield* JjVcsDriver.makeVcsDriverShape();
yield* driver.execute({
operation: "JjVcsDriver.test.env",
cwd: "/repo",
args: ["status"],
env: {
JJ_CONFIG: "/tmp/t3-jj-config.toml",
},
});
assert.deepStrictEqual(observedEnv, {
JJ_CONFIG: "/tmp/t3-jj-config.toml",
});
}).pipe(
Effect.provide(
Layer.mergeAll(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
observedEnv = input.env;
return processOutput("");
}),
}),
NodeServices.layer,
),
),
);
});
});
+518
View File
@@ -0,0 +1,518 @@
import { Context, Effect, FileSystem, Layer, Option } from "effect";
import { VcsOutputDecodeError, VcsProcessExitError, type VcsError } from "@t3tools/contracts";
import { VcsDriver, type VcsDriverShape } from "./VcsDriver.ts";
import { nowFreshness } from "./VcsFreshness.ts";
import { VcsProcess, type VcsProcessShape } from "./VcsProcess.ts";
export interface JjVcsDriverShape extends VcsDriverShape {
readonly capabilities: VcsDriverShape["capabilities"] & {
readonly kind: "jj";
readonly supportsBookmarks: true;
readonly supportsAtomicSnapshot: true;
readonly supportsWorktrees: false;
readonly ignoreClassifier: "git-compatible-fallback";
};
readonly currentChange: (cwd: string) => Effect.Effect<JjCurrentChange | null, VcsError>;
readonly listBookmarks: (cwd: string) => Effect.Effect<ReadonlyArray<JjBookmark>, VcsError>;
readonly listWorkspaces: (cwd: string) => Effect.Effect<ReadonlyArray<JjWorkspace>, VcsError>;
}
export interface JjCurrentChange {
readonly changeId: string;
readonly commitId: string | null;
readonly description: string | null;
}
export interface JjBookmark {
readonly name: string;
readonly target: string | null;
}
export interface JjWorkspace {
readonly name: string;
readonly path: string | null;
}
export class JjVcsDriver extends Context.Service<JjVcsDriver, JjVcsDriverShape>()(
"t3/vcs/JjVcsDriver",
) {}
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
const parts = input.split("\0");
if (parts.length === 0) return [];
if (truncated && parts[parts.length - 1]?.length) {
parts.pop();
}
return parts.filter((value) => value.length > 0);
}
function splitLineSeparatedPaths(input: string, truncated: boolean): string[] {
const lines = input.split(/\r?\n/g);
if (truncated && lines[lines.length - 1]?.length) {
lines.pop();
}
return lines.map((line) => line.trim()).filter((line) => line.length > 0);
}
function parseJjRemoteList(output: string): Array<{ name: string; url: string }> {
return output
.split(/\r?\n/g)
.map((line) => line.trim())
.flatMap((line) => {
if (line.length === 0) {
return [];
}
const [name, ...urlParts] = line.split(/\s+/g);
const url = urlParts.join(" ").trim();
return name && url ? [{ name, url }] : [];
});
}
function parseNullRecord(record: string): string[] {
return record.split("\0").map((value) => value.trim());
}
function decodeJjCurrentChange(
raw: string,
cwd: string,
): Effect.Effect<JjCurrentChange | null, VcsOutputDecodeError> {
const trimmed = raw.trim();
if (trimmed.length === 0) {
return Effect.succeed(null);
}
const [changeId, commitId, description] = parseNullRecord(trimmed);
if (!changeId) {
return Effect.fail(
new VcsOutputDecodeError({
operation: "JjVcsDriver.currentChange",
command: "jj log",
cwd,
detail: "jj current change output did not include a change id",
}),
);
}
return Effect.succeed({
changeId,
commitId: commitId || null,
description: description || null,
});
}
function decodeJjBookmarkList(raw: string): ReadonlyArray<JjBookmark> {
return raw
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const [name, target] = parseNullRecord(line);
return {
name: name ?? line,
target: target || null,
};
});
}
function decodeJjWorkspaceList(raw: string): ReadonlyArray<JjWorkspace> {
return raw
.split(/\r?\n/g)
.map((line) => line.trim())
.filter((line) => line.length > 0)
.map((line) => {
const [name, path] = parseNullRecord(line);
return {
name: name ?? line,
path: path || null,
};
});
}
function chunkPathsForCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {
const chunks: string[][] = [];
let chunk: string[] = [];
let chunkBytes = 0;
for (const relativePath of relativePaths) {
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
if (chunk.length > 0 && chunkBytes + relativePathBytes > CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
chunk.push(relativePath);
chunkBytes += relativePathBytes;
if (chunkBytes >= CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
}
if (chunk.length > 0) {
chunks.push(chunk);
}
return chunks;
}
const processCommand = (
process: VcsProcessShape,
command: string,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
options?: {
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
},
) =>
process.run({
operation,
command,
args,
cwd,
...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),
...(options?.env !== undefined ? { env: options.env } : {}),
...(options?.allowNonZeroExit !== undefined
? { allowNonZeroExit: options.allowNonZeroExit }
: {}),
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
...(options?.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes }
: {}),
});
const jjCommand = (
process: VcsProcessShape,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
options?: {
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
},
) => processCommand(process, "jj", operation, cwd, ["--no-pager", ...args], options);
const gitCommand = (
process: VcsProcessShape,
operation: string,
cwd: string,
args: ReadonlyArray<string>,
options?: Parameters<typeof processCommand>[5],
) => processCommand(process, "git", operation, cwd, args, options);
function fileSystemError(operation: string, cwd: string, detail: string, cause: unknown) {
return new VcsOutputDecodeError({
operation,
command: "git check-ignore",
cwd,
detail,
cause,
});
}
const makeScopedTempGitDir = (fileSystem: FileSystem.FileSystem, operation: string, cwd: string) =>
fileSystem
.makeTempDirectoryScoped({ prefix: "t3-jj-check-ignore-" })
.pipe(
Effect.mapError((cause) =>
fileSystemError(operation, cwd, "failed to create temp git dir", cause),
),
);
export const makeVcsDriverShape = Effect.fn("makeJjVcsDriverShape")(function* () {
const process = yield* VcsProcess;
const fileSystem = yield* FileSystem.FileSystem;
const capabilities = {
kind: "jj" as const,
supportsWorktrees: false as const,
supportsBookmarks: true as const,
supportsAtomicSnapshot: true as const,
supportsPushDefaultRemote: false as const,
ignoreClassifier: "git-compatible-fallback" as const,
};
const isInsideWorkTree: VcsDriverShape["isInsideWorkTree"] = (cwd) =>
jjCommand(process, "JjVcsDriver.isInsideWorkTree", cwd, ["root"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 4_096,
}).pipe(
Effect.map((result) => result.exitCode === 0 && result.stdout.trim().length > 0),
Effect.catch(() => Effect.succeed(false)),
);
const execute: VcsDriverShape["execute"] = (input) =>
jjCommand(process, input.operation, input.cwd, input.args, {
...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
...(input.env !== undefined ? { env: input.env } : {}),
...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),
...(input.truncateOutputAtMaxBytes !== undefined
? { truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes }
: {}),
});
const detectRepository: VcsDriverShape["detectRepository"] = Effect.fn("detectRepository")(
function* (cwd) {
const root = yield* jjCommand(process, "JjVcsDriver.detectRepository.root", cwd, ["root"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 4_096,
}).pipe(Effect.catch(() => Effect.succeed(null)));
if (!root || root.exitCode !== 0) {
return null;
}
const rootPath = root.stdout.trim();
if (rootPath.length === 0) {
return null;
}
return {
kind: "jj" as const,
rootPath,
metadataPath: `${rootPath.replace(/[\\/]$/g, "")}/.jj`,
freshness: yield* nowFreshness(),
};
},
);
const listWorkspaceFiles: VcsDriverShape["listWorkspaceFiles"] = (cwd) =>
jjCommand(process, "JjVcsDriver.listWorkspaceFiles", cwd, ["file", "list"], {
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
}).pipe(
Effect.flatMap((result) =>
result.exitCode === 0
? Effect.gen(function* () {
return {
paths: splitLineSeparatedPaths(result.stdout, result.stdoutTruncated),
truncated: result.stdoutTruncated,
freshness: yield* nowFreshness(),
};
})
: Effect.fail(
new VcsProcessExitError({
operation: "JjVcsDriver.listWorkspaceFiles",
command: "jj file list",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "jj file list failed",
}),
),
),
);
const listRemotes: VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")(function* (cwd) {
const result = yield* jjCommand(
process,
"JjVcsDriver.listRemotes",
cwd,
["git", "remote", "list"],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
},
);
if (result.exitCode !== 0) {
return {
remotes: [],
freshness: yield* nowFreshness(),
};
}
return {
remotes: parseJjRemoteList(result.stdout).map((remote) => ({
name: remote.name,
url: remote.url,
pushUrl: Option.none(),
isPrimary: remote.name === "origin",
})),
freshness: yield* nowFreshness(),
};
});
const currentChange: JjVcsDriverShape["currentChange"] = (cwd) =>
jjCommand(
process,
"JjVcsDriver.currentChange",
cwd,
[
"log",
"-r",
"@",
"--no-graph",
"--template",
'change_id ++ "\\0" ++ commit_id ++ "\\0" ++ description.first_line()',
],
{
timeoutMs: 5_000,
maxOutputBytes: 64 * 1024,
},
).pipe(Effect.flatMap((result) => decodeJjCurrentChange(result.stdout, cwd)));
const listBookmarks: JjVcsDriverShape["listBookmarks"] = (cwd) =>
jjCommand(
process,
"JjVcsDriver.listBookmarks",
cwd,
["bookmark", "list", "--template", 'name ++ "\\0" ++ target.commit_id() ++ "\\n"'],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 256 * 1024,
},
).pipe(
Effect.map((result) => (result.exitCode === 0 ? decodeJjBookmarkList(result.stdout) : [])),
);
const listWorkspaces: JjVcsDriverShape["listWorkspaces"] = (cwd) =>
jjCommand(
process,
"JjVcsDriver.listWorkspaces",
cwd,
["workspace", "list", "--template", 'name ++ "\\0" ++ root ++ "\\n"'],
{
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 256 * 1024,
},
).pipe(
Effect.map((result) => (result.exitCode === 0 ? decodeJjWorkspaceList(result.stdout) : [])),
);
const filterIgnoredPaths: VcsDriverShape["filterIgnoredPaths"] = Effect.fn("filterIgnoredPaths")(
function* (cwd, relativePaths) {
if (relativePaths.length === 0) {
return relativePaths;
}
const operation = "JjVcsDriver.filterIgnoredPaths";
const ignoredPaths = new Set<string>();
yield* Effect.scoped(
Effect.gen(function* () {
const gitDir = yield* makeScopedTempGitDir(fileSystem, operation, cwd);
const initResult = yield* gitCommand(
process,
operation,
cwd,
["--git-dir", gitDir, "init", "--bare"],
{
allowNonZeroExit: true,
},
);
if (initResult.exitCode !== 0) {
return yield* new VcsProcessExitError({
operation,
command: "git init --bare",
cwd,
exitCode: initResult.exitCode,
detail: initResult.stderr.trim() || "git init --bare failed",
});
}
for (const chunk of chunkPathsForCheckIgnore(relativePaths)) {
const result = yield* gitCommand(
process,
operation,
cwd,
[
"--git-dir",
gitDir,
"--work-tree",
cwd,
"check-ignore",
"--no-index",
"-z",
"--stdin",
],
{
stdin: `${chunk.join("\0")}\0`,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
},
);
if (result.exitCode !== 0 && result.exitCode !== 1) {
return yield* new VcsProcessExitError({
operation,
command: "git check-ignore",
cwd,
exitCode: result.exitCode,
detail: result.stderr.trim() || "git check-ignore failed",
});
}
for (const ignoredPath of splitNullSeparatedPaths(
result.stdout,
result.stdoutTruncated,
)) {
ignoredPaths.add(ignoredPath);
}
}
}),
);
if (ignoredPaths.size === 0) {
return relativePaths;
}
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
},
);
return {
capabilities,
execute,
detectRepository,
isInsideWorkTree,
listWorkspaceFiles,
listRemotes,
filterIgnoredPaths,
currentChange,
listBookmarks,
listWorkspaces,
} satisfies JjVcsDriverShape;
});
export const makeJjVcsDriver = Effect.fn("makeJjVcsDriver")(function* () {
const driver = yield* makeVcsDriverShape();
return JjVcsDriver.of(driver);
});
export const makeVcsDriver = Effect.fn("makeJjGenericVcsDriver")(function* () {
const driver = yield* makeVcsDriverShape();
return VcsDriver.of(driver);
});
export const layer = Layer.effect(JjVcsDriver, makeJjVcsDriver());
export const vcsLayer = Layer.effect(VcsDriver, makeVcsDriver());
+29
View File
@@ -0,0 +1,29 @@
import { Context, type Effect } from "effect";
import type {
VcsDriverCapabilities,
VcsError,
VcsListRemotesResult,
VcsListWorkspaceFilesResult,
VcsRepositoryIdentity,
} from "@t3tools/contracts";
import type { VcsProcessInput, VcsProcessOutput } from "./VcsProcess.ts";
export interface VcsDriverShape {
readonly capabilities: VcsDriverCapabilities;
readonly execute: (
input: Omit<VcsProcessInput, "command">,
) => Effect.Effect<VcsProcessOutput, VcsError>;
readonly detectRepository: (cwd: string) => Effect.Effect<VcsRepositoryIdentity | null, VcsError>;
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, VcsError>;
readonly listWorkspaceFiles: (
cwd: string,
) => Effect.Effect<VcsListWorkspaceFilesResult, VcsError>;
readonly listRemotes: (cwd: string) => Effect.Effect<VcsListRemotesResult, VcsError>;
readonly filterIgnoredPaths: (
cwd: string,
relativePaths: ReadonlyArray<string>,
) => Effect.Effect<ReadonlyArray<string>, VcsError>;
}
export class VcsDriver extends Context.Service<VcsDriver, VcsDriverShape>()("t3/vcs/VcsDriver") {}
@@ -0,0 +1,141 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
import { describe } from "vitest";
import { VcsProcess, type VcsProcessInput, type VcsProcessOutput } from "./VcsProcess.ts";
import { VcsProjectConfig } from "./VcsProjectConfig.ts";
import { VcsDriverRegistry, make as makeVcsDriverRegistry } from "./VcsDriverRegistry.ts";
const commandCalls = (calls: ReadonlyArray<VcsProcessInput>) =>
calls.map((call) => [call.command].concat(call.args));
const processOutput = (stdout: string, exitCode = 0, stderr = ""): VcsProcessOutput => ({
exitCode: ChildProcessSpawner.ExitCode(exitCode),
stdout,
stderr,
stdoutTruncated: false,
stderrTruncated: false,
});
describe("VcsDriverRegistry", () => {
it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => {
const calls: VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
Layer.provide(
Layer.mock(VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
const command = input.args.join(" ");
if (command === "rev-parse --is-inside-work-tree") {
return processOutput("true\n");
}
if (command === "rev-parse --show-toplevel") {
return processOutput("/repo\n");
}
if (command === "rev-parse --git-common-dir") {
return processOutput("/repo/.git\n");
}
return processOutput("");
}),
}),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry;
const first = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });
const second = yield* registry.resolve({ cwd: "/repo", requestedKind: "git" });
assert.equal(first.repository.rootPath, "/repo");
assert.equal(second.repository.rootPath, "/repo");
assert.deepStrictEqual(
calls.map((call) => call.args.join(" ")),
[
"rev-parse --is-inside-work-tree",
"rev-parse --show-toplevel",
"rev-parse --git-common-dir",
],
);
}).pipe(Effect.provide(layer));
});
it.effect("resolves an explicitly requested jj repository", () => {
const calls: VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
Layer.provide(
Layer.mock(VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
const command = input.args.join(" ");
if (input.command === "jj" && command === "--no-pager root") {
return processOutput("/repo\n");
}
return processOutput("", 1, "not found");
}),
}),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry;
const handle = yield* registry.resolve({ cwd: "/repo", requestedKind: "jj" });
assert.equal(handle.kind, "jj");
assert.equal(handle.repository.rootPath, "/repo");
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
}).pipe(Effect.provide(layer));
});
it.effect("prefers jj auto-detection before git for colocated repositories", () => {
const calls: VcsProcessInput[] = [];
const layer = Layer.effect(VcsDriverRegistry, makeVcsDriverRegistry()).pipe(
Layer.provide(
Layer.mock(VcsProjectConfig)({
resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"),
}),
),
Layer.provide(
Layer.mock(VcsProcess)({
run: (input) =>
Effect.sync(() => {
calls.push(input);
const command = input.args.join(" ");
if (input.command === "jj" && command === "--no-pager root") {
return processOutput("/repo\n");
}
if (input.command === "git") {
return processOutput("true\n");
}
return processOutput("", 1, "not found");
}),
}),
),
Layer.provide(NodeServices.layer),
);
return Effect.gen(function* () {
const registry = yield* VcsDriverRegistry;
const handle = yield* registry.resolve({ cwd: "/repo" });
assert.equal(handle.kind, "jj");
assert.equal(handle.repository.rootPath, "/repo");
assert.deepStrictEqual(commandCalls(calls), [["jj", "--no-pager", "root"]]);
}).pipe(Effect.provide(layer));
});
});
+158
View File
@@ -0,0 +1,158 @@
import { Cache, Context, Duration, Effect, Exit, Layer } from "effect";
import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/contracts";
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
import * as JjVcsDriver from "./JjVcsDriver.ts";
import * as VcsProjectConfig from "./VcsProjectConfig.ts";
import type { VcsDriverShape } from "./VcsDriver.ts";
const DETECTION_CACHE_CAPACITY = 2_048;
const DETECTION_CACHE_TTL = Duration.seconds(2);
export interface VcsDriverResolveInput {
readonly cwd: string;
readonly requestedKind?: VcsDriverKind | "auto";
}
export interface VcsDriverHandle {
readonly kind: VcsDriverKind;
readonly repository: VcsRepositoryIdentity;
readonly driver: VcsDriverShape;
}
export interface VcsDriverRegistryShape {
readonly detect: (
input: VcsDriverResolveInput,
) => Effect.Effect<VcsDriverHandle | null, VcsError>;
readonly resolve: (input: VcsDriverResolveInput) => Effect.Effect<VcsDriverHandle, VcsError>;
}
export class VcsDriverRegistry extends Context.Service<VcsDriverRegistry, VcsDriverRegistryShape>()(
"t3/vcs/VcsDriverRegistry",
) {}
const unsupported = (operation: string, kind: VcsDriverKind, detail: string) =>
new VcsUnsupportedOperationError({
operation,
kind,
detail,
});
function detectionCacheKey(input: {
readonly cwd: string;
readonly requestedKind: VcsDriverKind | "auto";
}): string {
return `${input.requestedKind}\0${input.cwd}`;
}
function parseDetectionCacheKey(key: string): {
readonly cwd: string;
readonly requestedKind: VcsDriverKind | "auto";
} {
const separatorIndex = key.indexOf("\0");
if (separatorIndex === -1) {
return {
cwd: key,
requestedKind: "auto",
};
}
return {
requestedKind: key.slice(0, separatorIndex) as VcsDriverKind | "auto",
cwd: key.slice(separatorIndex + 1),
};
}
export const make = Effect.fn("makeVcsDriverRegistry")(function* () {
const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;
const git = yield* GitVcsDriver.makeVcsDriverShape();
const jj = yield* JjVcsDriver.makeVcsDriverShape();
const drivers: Partial<Record<VcsDriverKind, VcsDriverShape>> = {
git,
jj,
};
const detectWithDriver = Effect.fn("VcsDriverRegistry.detectWithDriver")(function* (
kind: VcsDriverKind,
driver: VcsDriverShape,
cwd: string,
) {
const repository = yield* driver.detectRepository(cwd);
if (!repository) {
return null;
}
return {
kind,
repository,
driver,
} satisfies VcsDriverHandle;
});
const detectResolvedKind = Effect.fn("VcsDriverRegistry.detectResolvedKind")(function* (input: {
readonly cwd: string;
readonly requestedKind: VcsDriverKind | "auto";
}) {
const requestedKind = input.requestedKind;
if (requestedKind !== "auto" && requestedKind !== "unknown") {
const driver = drivers[requestedKind];
if (!driver) {
return yield* unsupported(
"VcsDriverRegistry.detect",
requestedKind,
`No ${requestedKind} VCS driver is registered.`,
);
}
return yield* detectWithDriver(requestedKind, driver, input.cwd);
}
const jjDetected = yield* detectWithDriver("jj", jj, input.cwd);
if (jjDetected) {
return jjDetected;
}
return yield* detectWithDriver("git", git, input.cwd);
});
const detectionCache = yield* Cache.makeWith<string, VcsDriverHandle | null, VcsError>(
(key) => detectResolvedKind(parseDetectionCacheKey(key)),
{
capacity: DETECTION_CACHE_CAPACITY,
timeToLive: (exit) => (Exit.isSuccess(exit) ? DETECTION_CACHE_TTL : Duration.zero),
},
);
const detect: VcsDriverRegistryShape["detect"] = Effect.fn("VcsDriverRegistry.detect")(
function* (input) {
const requestedKind = yield* projectConfig.resolveKind(input);
return yield* Cache.get(detectionCache, detectionCacheKey({ cwd: input.cwd, requestedKind }));
},
);
const resolve: VcsDriverRegistryShape["resolve"] = Effect.fn("VcsDriverRegistry.resolve")(
function* (input) {
const detected = yield* detect(input);
if (detected) {
return detected;
}
const requestedKind = input.requestedKind ?? "auto";
return yield* unsupported(
"VcsDriverRegistry.resolve",
requestedKind === "auto" ? "unknown" : requestedKind,
requestedKind === "auto"
? `No supported VCS repository was detected at ${input.cwd}.`
: `No ${requestedKind} repository was detected at ${input.cwd}.`,
);
},
);
return VcsDriverRegistry.of({
detect,
resolve,
});
});
export const layer = Layer.effect(VcsDriverRegistry, make()).pipe(
Layer.provide(VcsProjectConfig.layer),
);
+10
View File
@@ -0,0 +1,10 @@
import { DateTime, Effect, Option } from "effect";
export const nowFreshness = Effect.fn("VcsFreshness.nowFreshness")(function* () {
const now = yield* DateTime.now;
return {
source: "live-local" as const,
observedAt: now,
expiresAt: Option.none(),
};
});
+259
View File
@@ -0,0 +1,259 @@
import { Duration, Context, Effect, Layer, Option, PlatformError, Sink, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
VcsOutputDecodeError,
type VcsError,
VcsProcessExitError,
VcsProcessSpawnError,
VcsProcessTimeoutError,
} from "@t3tools/contracts";
export interface VcsProcessInput {
readonly operation: string;
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd: string;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}
export interface VcsProcessOutput {
readonly exitCode: ChildProcessSpawner.ExitCode;
readonly stdout: string;
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
export interface VcsProcessCollectedText {
readonly text: string;
readonly truncated: boolean;
}
export interface VcsProcessHandle {
readonly pid: ChildProcessSpawner.ProcessId;
readonly stdin: Sink.Sink<void, Uint8Array, never, VcsError>;
readonly stdout: Stream.Stream<Uint8Array, VcsError>;
readonly stderr: Stream.Stream<Uint8Array, VcsError>;
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode, VcsError>;
readonly writeStdin: (input: string) => Effect.Effect<void, VcsError>;
}
export interface VcsProcessShape {
readonly withProcess: <A, E, R>(
input: VcsProcessInput,
use: (handle: VcsProcessHandle) => Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | VcsError, R>;
readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
}
export class VcsProcess extends Context.Service<VcsProcess, VcsProcessShape>()(
"t3/vcs/VcsProcess",
) {}
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
function commandLabel(command: string, args: ReadonlyArray<string>): string {
return [command, ...args].join(" ");
}
function outputDecodeError(
input: VcsProcessInput,
detail: string,
cause: unknown,
): VcsOutputDecodeError {
return new VcsOutputDecodeError({
operation: input.operation,
command: commandLabel(input.command, input.args),
cwd: input.cwd,
detail,
cause,
});
}
export const collectText = Effect.fn("VcsProcess.collectText")(function* (input: {
readonly operation: string;
readonly command: string;
readonly cwd: string;
readonly stream: Stream.Stream<Uint8Array, VcsError>;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
}) {
const decoder = new TextDecoder();
let text = "";
let bytes = 0;
let truncated = false;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false;
yield* Stream.runForEach(input.stream, (chunk) =>
Effect.sync(() => {
if (truncated) return;
const remainingBytes = maxOutputBytes - bytes;
if (remainingBytes <= 0) {
truncated = true;
if (truncateOutputAtMaxBytes) {
text += OUTPUT_TRUNCATED_MARKER;
}
return;
}
const nextChunk = chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
text += decoder.decode(nextChunk, { stream: true });
bytes += nextChunk.byteLength;
if (chunk.byteLength > remainingBytes) {
truncated = true;
if (truncateOutputAtMaxBytes) {
text += OUTPUT_TRUNCATED_MARKER;
}
}
}),
);
if (!truncated) {
text += decoder.decode();
}
return { text, truncated } satisfies VcsProcessCollectedText;
});
export const make = Effect.fn("makeVcsProcess")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const spawn = Effect.fn("VcsProcess.spawn")(function* (input: VcsProcessInput) {
const label = commandLabel(input.command, input.args);
const child = yield* spawner
.spawn(
ChildProcess.make(input.command, [...input.args], {
cwd: input.cwd,
env: {
...process.env,
...input.env,
},
}),
)
.pipe(
Effect.mapError(
(cause) =>
new VcsProcessSpawnError({
operation: input.operation,
command: label,
cwd: input.cwd,
cause,
}),
),
);
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
const mapStreamError = (streamName: "stdout" | "stderr") =>
Stream.mapError((cause: PlatformError.PlatformError) =>
outputDecodeError(input, `failed to read process ${streamName}`, cause),
);
const mapEffectError = (detail: string) =>
Effect.mapError((cause: PlatformError.PlatformError) =>
outputDecodeError(input, detail, cause),
);
const writeStdin = (stdin: string) =>
Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(
mapEffectError("failed to write process stdin"),
);
return {
pid: child.pid,
stdin: child.stdin.pipe(
Sink.mapError((cause) => outputDecodeError(input, "failed to write process stdin", cause)),
),
stdout: child.stdout.pipe(mapStreamError("stdout")),
stderr: child.stderr.pipe(mapStreamError("stderr")),
exitCode: child.exitCode.pipe(mapEffectError("failed to read process exit code")),
writeStdin,
} satisfies VcsProcessHandle;
});
const withProcess: VcsProcessShape["withProcess"] = (input, use) =>
Effect.scoped(spawn(input).pipe(Effect.flatMap(use)));
const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const label = commandLabel(input.command, input.args);
const runProcess = Effect.gen(function* () {
const [stdout, stderr, exitCode] = yield* withProcess(input, (child) =>
Effect.all(
[
collectText({
operation: input.operation,
command: label,
cwd: input.cwd,
stream: child.stdout,
maxOutputBytes,
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
}),
collectText({
operation: input.operation,
command: label,
cwd: input.cwd,
stream: child.stderr,
maxOutputBytes,
truncateOutputAtMaxBytes: input.truncateOutputAtMaxBytes ?? false,
}),
child.exitCode,
input.stdin === undefined ? Effect.void : child.writeStdin(input.stdin),
],
{ concurrency: "unbounded" },
),
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
if (!input.allowNonZeroExit && exitCode !== 0) {
return yield* new VcsProcessExitError({
operation: input.operation,
command: label,
cwd: input.cwd,
exitCode,
detail: stderr.text.trim() || `${label} exited with code ${exitCode}.`,
});
}
return {
exitCode,
stdout: stdout.text,
stderr: stderr.text,
stdoutTruncated: stdout.truncated,
stderrTruncated: stderr.truncated,
} satisfies VcsProcessOutput;
});
return yield* runProcess.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(timeoutMs)),
Effect.flatMap((result) =>
Option.match(result, {
onSome: Effect.succeed,
onNone: () =>
Effect.fail(
new VcsProcessTimeoutError({
operation: input.operation,
command: label,
cwd: input.cwd,
timeoutMs,
}),
),
}),
),
);
});
return VcsProcess.of({ withProcess, run });
});
export const layer = Layer.effect(VcsProcess, make());
@@ -0,0 +1,67 @@
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer, Path } from "effect";
import { describe } from "vitest";
import { VcsProjectConfig, layer as VcsProjectConfigLayer } from "./VcsProjectConfig.ts";
const TestLayer = VcsProjectConfigLayer.pipe(
Layer.provide(NodeServices.layer),
Layer.provideMerge(NodeServices.layer),
);
describe("VcsProjectConfig", () => {
it.layer(TestLayer)("uses an explicit requested VCS kind before config", (it) => {
it.effect("returns the requested kind", () =>
Effect.gen(function* () {
const config = yield* VcsProjectConfig;
const kind = yield* config.resolveKind({
cwd: "/repo",
requestedKind: "jj",
});
assert.equal(kind, "jj");
}),
);
});
it.layer(TestLayer)("discovers .t3code/vcs.json from nested workspaces", (it) => {
it.effect("returns the configured kind", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
const nested = path.join(root, "packages", "app");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.makeDirectory(nested, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
JSON.stringify({ vcs: { kind: "jj" } }),
);
const config = yield* VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: nested });
assert.equal(kind, "jj");
}),
);
});
it.layer(TestLayer)("falls back to auto when no config exists", (it) => {
it.effect("returns auto", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const config = yield* VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
});
});
+117
View File
@@ -0,0 +1,117 @@
import { Context, Effect, FileSystem, Layer, Path, Schema } from "effect";
import { VcsDriverKind, type VcsDriverKind as VcsDriverKindType } from "@t3tools/contracts";
const ProjectVcsConfig = Schema.Struct({
vcs: Schema.optional(
Schema.Struct({
kind: Schema.optional(VcsDriverKind),
}),
),
vcsKind: Schema.optional(VcsDriverKind),
});
interface ProjectVcsConfigFile {
readonly vcs?:
| {
readonly kind?: VcsDriverKindType | undefined;
}
| undefined;
readonly vcsKind?: VcsDriverKindType | undefined;
}
export interface VcsProjectConfigResolveInput {
readonly cwd: string;
readonly requestedKind?: VcsDriverKindType | "auto";
}
export interface VcsProjectConfigShape {
readonly resolveKind: (
input: VcsProjectConfigResolveInput,
) => Effect.Effect<VcsDriverKindType | "auto">;
}
export class VcsProjectConfig extends Context.Service<VcsProjectConfig, VcsProjectConfigShape>()(
"t3/vcs/VcsProjectConfig",
) {}
function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto" {
return config.vcs?.kind ?? config.vcsKind ?? "auto";
}
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return Schema.is(ProjectVcsConfig)(parsed) ? parsed : null;
} catch {
return null;
}
}
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const findConfigPath = Effect.fn("VcsProjectConfig.findConfigPath")(function* (cwd: string) {
let current = cwd;
while (true) {
const candidate = path.join(current, ".t3code", "vcs.json");
if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
return candidate;
}
const parent = path.dirname(current);
if (parent === current) {
return null;
}
current = parent;
}
});
const readConfiguredKind = Effect.fn("VcsProjectConfig.readConfiguredKind")(function* (
configPath: string,
) {
const raw = yield* fileSystem.readFileString(configPath).pipe(
Effect.catch((error) =>
Effect.logWarning("failed to read VCS project config", {
configPath,
error,
}).pipe(Effect.as(null)),
),
);
if (raw === null) {
return "auto" as const;
}
const parsed = parseConfig(raw);
if (parsed === null) {
yield* Effect.logWarning("invalid VCS project config", {
configPath,
});
return "auto" as const;
}
return configuredKind(parsed);
});
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
"VcsProjectConfig.resolveKind",
)(function* (input) {
if (input.requestedKind !== undefined && input.requestedKind !== "auto") {
return input.requestedKind;
}
const configPath = yield* findConfigPath(input.cwd);
if (configPath === null) {
return "auto";
}
return yield* readConfiguredKind(configPath);
});
return VcsProjectConfig.of({
resolveKind,
});
});
export const layer = Layer.effect(VcsProjectConfig, make());
@@ -1,52 +1,56 @@
import { assert, it } from "@effect/vitest";
import { Deferred, Effect, Exit, Layer, Option, Scope, Stream } from "effect";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Deferred, Effect, Exit, FileSystem, Layer, Option, Path, Scope, Stream } from "effect";
import type {
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusResult,
GitStatusStreamEvent,
VcsStatusLocalResult,
VcsStatusRemoteResult,
VcsStatusResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { describe } from "vitest";
import { GitStatusBroadcaster } from "../Services/GitStatusBroadcaster.ts";
import { GitStatusBroadcasterLive } from "./GitStatusBroadcaster.ts";
import { type GitManagerShape, GitManager } from "../Services/GitManager.ts";
import {
VcsStatusBroadcaster,
layer as VcsStatusBroadcasterLayer,
} from "./VcsStatusBroadcaster.ts";
import { GitWorkflowService, type GitWorkflowServiceShape } from "../git/GitWorkflowService.ts";
const baseLocalStatus: GitStatusLocalResult = {
const baseLocalStatus: VcsStatusLocalResult = {
kind: "git",
isRepo: true,
hostingProvider: {
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/status-broadcast",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/status-broadcast",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
};
const baseRemoteStatus: GitStatusRemoteResult = {
const baseRemoteStatus: VcsStatusRemoteResult = {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: null,
};
const baseStatus: GitStatusResult = {
const baseStatus: VcsStatusResult = {
...baseLocalStatus,
...baseRemoteStatus,
};
function makeTestLayer(state: {
currentLocalStatus: GitStatusLocalResult;
currentRemoteStatus: GitStatusRemoteResult | null;
currentLocalStatus: VcsStatusLocalResult;
currentRemoteStatus: VcsStatusRemoteResult | null;
localStatusCalls: number;
remoteStatusCalls: number;
localInvalidationCalls: number;
remoteInvalidationCalls: number;
}) {
const gitManager: GitManagerShape = {
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
@@ -57,7 +61,6 @@ function makeTestLayer(state: {
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
@@ -66,18 +69,16 @@ function makeTestLayer(state: {
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () => Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
};
});
return GitStatusBroadcasterLive.pipe(Layer.provide(Layer.succeed(GitManager, gitManager)));
return VcsStatusBroadcasterLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
}
describe("GitStatusBroadcasterLive", () => {
it.effect("reuses the cached git status across repeated reads", () => {
describe("VcsStatusBroadcaster", () => {
it.effect("reuses the cached VCS status across repeated reads", () => {
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
@@ -88,7 +89,7 @@ describe("GitStatusBroadcasterLive", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster;
const first = yield* broadcaster.getStatus({ cwd: "/repo" });
const second = yield* broadcaster.getStatus({ cwd: "/repo" });
@@ -113,12 +114,12 @@ describe("GitStatusBroadcasterLive", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
branch: "feature/updated-status",
refName: "feature/updated-status",
};
state.currentRemoteStatus = {
...baseRemoteStatus,
@@ -154,12 +155,12 @@ describe("GitStatusBroadcasterLive", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const broadcaster = yield* VcsStatusBroadcaster;
const initial = yield* broadcaster.getStatus({ cwd: "/repo" });
state.currentLocalStatus = {
...baseLocalStatus,
branch: "feature/local-only-refresh",
refName: "feature/local-only-refresh",
hasWorkingTreeChanges: true,
};
@@ -179,6 +180,66 @@ describe("GitStatusBroadcasterLive", () => {
}).pipe(Effect.provide(makeTestLayer(state)));
});
it.effect("normalizes symlinked CWDs before cache lookup and workflow calls", () => {
const seenCwds: string[] = [];
const state = {
currentLocalStatus: baseLocalStatus,
currentRemoteStatus: baseRemoteStatus,
localStatusCalls: 0,
remoteStatusCalls: 0,
localInvalidationCalls: 0,
remoteInvalidationCalls: 0,
};
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: (input) =>
Effect.sync(() => {
seenCwds.push(input.cwd);
state.remoteStatusCalls += 1;
return state.currentRemoteStatus;
}),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>);
const testLayer = VcsStatusBroadcasterLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const realDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-status-real-",
});
const linkParent = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-status-link-",
});
const linkDir = path.join(linkParent, "repo-link");
yield* fileSystem.symlink(realDir, linkDir);
const realPath = yield* fileSystem.realPath(realDir);
const broadcaster = yield* VcsStatusBroadcaster;
yield* broadcaster.getStatus({ cwd: linkDir });
yield* broadcaster.getStatus({ cwd: realDir });
assert.deepStrictEqual(seenCwds, [realPath, realPath]);
assert.equal(state.localStatusCalls, 1);
assert.equal(state.remoteStatusCalls, 1);
}).pipe(Effect.provide(testLayer));
});
it.effect("streams a local snapshot first and remote updates later", () => {
const state = {
currentLocalStatus: baseLocalStatus,
@@ -190,9 +251,9 @@ describe("GitStatusBroadcasterLive", () => {
};
return Effect.gen(function* () {
const broadcaster = yield* GitStatusBroadcaster;
const snapshotDeferred = yield* Deferred.make<GitStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<GitStatusStreamEvent>();
const broadcaster = yield* VcsStatusBroadcaster;
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
const remoteUpdatedDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) => {
if (event._tag === "snapshot") {
return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore);
@@ -211,11 +272,11 @@ describe("GitStatusBroadcasterLive", () => {
_tag: "snapshot",
local: baseLocalStatus,
remote: null,
} satisfies GitStatusStreamEvent);
} satisfies VcsStatusStreamEvent);
assert.deepStrictEqual(remoteUpdated, {
_tag: "remoteUpdated",
remote: baseRemoteStatus,
} satisfies GitStatusStreamEvent);
} satisfies VcsStatusStreamEvent);
}).pipe(Effect.provide(makeTestLayer(state)));
});
@@ -230,47 +291,40 @@ describe("GitStatusBroadcasterLive", () => {
};
let remoteInterruptedDeferred: Deferred.Deferred<void, never> | null = null;
let remoteStartedDeferred: Deferred.Deferred<void, never> | null = null;
const testLayer = GitStatusBroadcasterLive.pipe(
Layer.provide(
Layer.succeed(GitManager, {
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<GitStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
status: () => Effect.die("status should not be called in this test"),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
invalidateStatus: () => Effect.die("invalidateStatus should not be called in this test"),
resolvePullRequest: () =>
Effect.die("resolvePullRequest should not be called in this test"),
preparePullRequestThread: () =>
Effect.die("preparePullRequestThread should not be called in this test"),
runStackedAction: () => Effect.die("runStackedAction should not be called in this test"),
} satisfies GitManagerShape),
),
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
localStatus: () =>
Effect.sync(() => {
state.localStatusCalls += 1;
return state.currentLocalStatus;
}),
remoteStatus: () =>
Effect.sync(() => {
state.remoteStatusCalls += 1;
}).pipe(
Effect.andThen(
remoteStartedDeferred
? Deferred.succeed(remoteStartedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
Effect.andThen(Effect.never as Effect.Effect<VcsStatusRemoteResult | null, never>),
Effect.onInterrupt(() =>
remoteInterruptedDeferred
? Deferred.succeed(remoteInterruptedDeferred, undefined).pipe(Effect.ignore)
: Effect.void,
),
),
invalidateLocalStatus: () =>
Effect.sync(() => {
state.localInvalidationCalls += 1;
}),
invalidateRemoteStatus: () =>
Effect.sync(() => {
state.remoteInvalidationCalls += 1;
}),
} satisfies Partial<GitWorkflowServiceShape>);
const testLayer = VcsStatusBroadcasterLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(gitWorkflowLayer),
);
return Effect.gen(function* () {
@@ -279,9 +333,9 @@ describe("GitStatusBroadcasterLive", () => {
remoteInterruptedDeferred = remoteInterrupted;
remoteStartedDeferred = remoteStarted;
const broadcaster = yield* GitStatusBroadcaster;
const firstSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const secondSnapshot = yield* Deferred.make<GitStatusStreamEvent>();
const broadcaster = yield* VcsStatusBroadcaster;
const firstSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
const secondSnapshot = yield* Deferred.make<VcsStatusStreamEvent>();
const firstScope = yield* Scope.make();
const secondScope = yield* Scope.make();
yield* Stream.runForEach(broadcaster.streamStatus({ cwd: "/repo" }), (event) =>
@@ -302,11 +356,11 @@ describe("GitStatusBroadcasterLive", () => {
assert.equal(state.remoteStatusCalls, 1);
yield* Scope.close(firstScope, Exit.void);
assert.equal(Option.isNone(yield* Deferred.poll(remoteInterrupted)), true);
assert.isTrue(Option.isNone(yield* Deferred.poll(remoteInterrupted)));
yield* Scope.close(secondScope, Exit.void).pipe(Effect.forkScoped);
yield* Deferred.await(remoteInterrupted);
assert.equal(Option.isSome(yield* Deferred.poll(remoteInterrupted)), true);
assert.isTrue(Option.isSome(yield* Deferred.poll(remoteInterrupted)));
}).pipe(Effect.provide(testLayer));
});
});
+339
View File
@@ -0,0 +1,339 @@
import {
Duration,
Effect,
Exit,
FileSystem,
Fiber,
Layer,
PubSub,
Ref,
Scope,
Stream,
SynchronizedRef,
} from "effect";
import type {
GitManagerServiceError,
VcsStatusInput,
VcsStatusLocalResult,
VcsStatusRemoteResult,
VcsStatusResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { Context } from "effect";
import { mergeGitStatusParts } from "@t3tools/shared/git";
import { GitWorkflowService } from "../git/GitWorkflowService.ts";
const VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
interface VcsStatusChange {
readonly cwd: string;
readonly event: VcsStatusStreamEvent;
}
interface CachedValue<T> {
readonly fingerprint: string;
readonly value: T;
}
interface CachedVcsStatus {
readonly local: CachedValue<VcsStatusLocalResult> | null;
readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;
}
interface ActiveRemotePoller {
readonly fiber: Fiber.Fiber<void, never>;
readonly subscriberCount: number;
}
export interface VcsStatusBroadcasterShape {
readonly getStatus: (
input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly refreshLocalStatus: (
cwd: string,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
readonly streamStatus: (
input: VcsStatusInput,
) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
}
export class VcsStatusBroadcaster extends Context.Service<
VcsStatusBroadcaster,
VcsStatusBroadcasterShape
>()("t3/vcs/VcsStatusBroadcaster") {}
function fingerprintStatusPart(status: unknown): string {
return JSON.stringify(status);
}
export const layer = Layer.effect(
VcsStatusBroadcaster,
Effect.gen(function* () {
const workflow = yield* GitWorkflowService;
const fileSystem = yield* FileSystem.FileSystem;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<VcsStatusChange>(),
(pubsub) => PubSub.shutdown(pubsub),
);
const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
Scope.close(scope, Exit.void),
);
const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
const normalizeCwd = (cwd: string) =>
fileSystem.realPath(cwd).pipe(Effect.catch(() => Effect.succeed(cwd)));
const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
cwd: string,
) {
return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
});
const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
const nextLocal = {
fingerprint: fingerprintStatusPart(local),
value: local,
} satisfies CachedValue<VcsStatusLocalResult>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
local: nextLocal,
});
return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "localUpdated",
local,
},
});
}
return local;
},
);
const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
function* (
cwd: string,
remote: VcsStatusRemoteResult | null,
options?: { publish?: boolean },
) {
const nextRemote = {
fingerprint: fingerprintStatusPart(remote),
value: remote,
} satisfies CachedValue<VcsStatusRemoteResult | null>;
const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
const previous = cache.get(cwd) ?? { local: null, remote: null };
const nextCache = new Map(cache);
nextCache.set(cwd, {
...previous,
remote: nextRemote,
});
return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
});
if (options?.publish && shouldPublish) {
yield* PubSub.publish(changesPubSub, {
cwd,
event: {
_tag: "remoteUpdated",
remote,
},
});
}
return remote;
},
);
const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
cwd: string,
) {
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local);
});
const loadRemoteStatus = Effect.fn("VcsStatusBroadcaster.loadRemoteStatus")(function* (
cwd: string,
) {
const remote = yield* workflow.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote);
});
const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
cwd: string,
) {
const cached = yield* getCachedStatus(cwd);
if (cached?.local) {
return cached.local.value;
}
return yield* loadLocalStatus(cwd);
});
const getOrLoadRemoteStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadRemoteStatus")(
function* (cwd: string) {
const cached = yield* getCachedStatus(cwd);
if (cached?.remote) {
return cached.remote.value;
}
return yield* loadRemoteStatus(cwd);
},
);
const getStatus: VcsStatusBroadcasterShape["getStatus"] = Effect.fn(
"VcsStatusBroadcaster.getStatus",
)(function* (input) {
const cwd = yield* normalizeCwd(input.cwd);
const [local, remote] = yield* Effect.all([
getOrLoadLocalStatus(cwd),
getOrLoadRemoteStatus(cwd),
]);
return mergeGitStatusParts(local, remote);
});
const refreshLocalStatus: VcsStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshLocalStatus",
)(function* (rawCwd) {
const cwd = yield* normalizeCwd(rawCwd);
yield* workflow.invalidateLocalStatus(cwd);
const local = yield* workflow.localStatus({ cwd });
return yield* updateCachedLocalStatus(cwd, local, { publish: true });
});
const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
cwd: string,
) {
yield* workflow.invalidateRemoteStatus(cwd);
const remote = yield* workflow.remoteStatus({ cwd });
return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
});
const refreshStatus: VcsStatusBroadcasterShape["refreshStatus"] = Effect.fn(
"VcsStatusBroadcaster.refreshStatus",
)(function* (rawCwd) {
const cwd = yield* normalizeCwd(rawCwd);
const [local, remote] = yield* Effect.all([
refreshLocalStatus(cwd),
refreshRemoteStatus(cwd),
]);
return mergeGitStatusParts(local, remote);
});
const makeRemoteRefreshLoop = (cwd: string) => {
const logRefreshFailure = (error: Error) =>
Effect.logWarning("VCS remote status refresh failed", {
cwd,
detail: error.message,
});
return refreshRemoteStatus(cwd).pipe(
Effect.catch(logRefreshFailure),
Effect.andThen(
Effect.forever(
Effect.sleep(VCS_STATUS_REFRESH_INTERVAL).pipe(
Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
),
),
),
);
};
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
cwd: string,
) {
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (existing) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount + 1,
});
return Effect.succeed([undefined, nextPollers] as const);
}
return makeRemoteRefreshLoop(cwd).pipe(
Effect.forkIn(broadcasterScope),
Effect.map((fiber) => {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
fiber,
subscriberCount: 1,
});
return [undefined, nextPollers] as const;
}),
);
});
});
const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
cwd: string,
) {
const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
const existing = activePollers.get(cwd);
if (!existing) {
return [null, activePollers] as const;
}
if (existing.subscriberCount > 1) {
const nextPollers = new Map(activePollers);
nextPollers.set(cwd, {
...existing,
subscriberCount: existing.subscriberCount - 1,
});
return [null, nextPollers] as const;
}
const nextPollers = new Map(activePollers);
nextPollers.delete(cwd);
return [existing.fiber, nextPollers] as const;
});
if (pollerToInterrupt) {
yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
}
});
const streamStatus: VcsStatusBroadcasterShape["streamStatus"] = (input) =>
Stream.unwrap(
Effect.gen(function* () {
const cwd = yield* normalizeCwd(input.cwd);
const subscription = yield* PubSub.subscribe(changesPubSub);
const initialLocal = yield* getOrLoadLocalStatus(cwd);
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
yield* retainRemotePoller(cwd);
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
return Stream.concat(
Stream.make({
_tag: "snapshot" as const,
local: initialLocal,
remote: initialRemote,
}),
Stream.fromSubscription(subscription).pipe(
Stream.filter((event) => event.cwd === cwd),
Stream.map((event) => event.event),
),
).pipe(Stream.ensuring(release));
}),
);
return VcsStatusBroadcaster.of({
getStatus,
refreshLocalStatus,
refreshStatus,
streamStatus,
});
}),
);
@@ -0,0 +1,154 @@
import { assert, it } from "@effect/vitest";
import { DateTime, Option } from "effect";
import { Effect, FileSystem, Layer, Path, type PlatformError, type Scope } from "effect";
import { describe } from "vitest";
import type { VcsDriverKind } from "@t3tools/contracts";
import { VcsDriver } from "../VcsDriver.ts";
export interface VcsDriverFixture<R, E> {
readonly createRepo: (cwd: string) => Effect.Effect<void, E, R>;
readonly writeFile: (
cwd: string,
relativePath: string,
contents: string,
) => Effect.Effect<void, E, R | FileSystem.FileSystem | Path.Path>;
readonly trackFile?: (cwd: string, relativePath: string) => Effect.Effect<void, E, R>;
readonly commit?: (cwd: string, message: string) => Effect.Effect<void, E, R>;
readonly ignorePath: (
cwd: string,
pattern: string,
) => Effect.Effect<void, E, R | FileSystem.FileSystem | Path.Path>;
}
export interface VcsDriverContractSuiteInput<R, E> {
readonly name: string;
readonly kind: VcsDriverKind;
readonly layer: Layer.Layer<VcsDriver | R | FileSystem.FileSystem | Path.Path, E, never>;
readonly fixture: VcsDriverFixture<R, E>;
}
export function runVcsDriverContractSuite<R, E>(input: VcsDriverContractSuiteInput<R, E>) {
const makeTmpDir = (
prefix = `t3-${input.kind}-vcs-contract-`,
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
it.layer(input.layer)(`${input.name} VCS driver contract`, (it) => {
describe("repository detection", () => {
it.effect("returns null outside a repository", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
assert.equal(yield* driver.detectRepository(cwd), null);
assert.equal(yield* driver.isInsideWorkTree(cwd), false);
}),
);
it.effect("detects repository identity inside a repository and nested directories", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.writeFile(cwd, "src/index.ts", "export const value = 1;\n");
const fileSystem = yield* FileSystem.FileSystem;
const realCwd = yield* fileSystem.realPath(cwd);
const identity = yield* driver.detectRepository(cwd);
assert.equal(identity?.kind, input.kind);
assert.isTrue(identity?.rootPath.endsWith(realCwd));
assert.equal(identity?.freshness.source, "live-local");
assert.isTrue(DateTime.isDateTime(identity?.freshness.observedAt));
assert.isTrue(Option.isNone(identity?.freshness.expiresAt ?? Option.none()));
assert.equal(yield* driver.isInsideWorkTree(cwd), true);
const path = yield* Path.Path;
const nestedDir = path.join(cwd, "src");
const nestedIdentity = yield* driver.detectRepository(nestedDir);
assert.equal(nestedIdentity?.rootPath, identity?.rootPath);
assert.equal(yield* driver.isInsideWorkTree(nestedDir), true);
}),
);
});
describe("workspace files", () => {
it.effect("lists tracked and untracked non-ignored files", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.writeFile(cwd, "tracked.ts", "export const tracked = true;\n");
if (input.fixture.trackFile && input.fixture.commit) {
yield* input.fixture.trackFile(cwd, "tracked.ts");
yield* input.fixture.commit(cwd, "Track file");
}
yield* input.fixture.writeFile(cwd, "untracked.ts", "export const untracked = true;\n");
const result = yield* driver.listWorkspaceFiles(cwd);
assert.include(result.paths, "tracked.ts");
assert.include(result.paths, "untracked.ts");
assert.equal(result.truncated, false);
assert.equal(result.freshness.source, "live-local");
assert.isTrue(DateTime.isDateTime(result.freshness.observedAt));
assert.isTrue(Option.isNone(result.freshness.expiresAt));
}),
);
it.effect("excludes ignored files from workspace listing", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.ignorePath(cwd, "*.log");
yield* input.fixture.writeFile(cwd, "included.ts", "export const included = true;\n");
yield* input.fixture.writeFile(cwd, "debug.log", "ignore me\n");
yield* input.fixture.writeFile(cwd, "nested/error.log", "ignore me too\n");
const result = yield* driver.listWorkspaceFiles(cwd);
assert.include(result.paths, "included.ts");
assert.notInclude(result.paths, "debug.log");
assert.notInclude(result.paths, "nested/error.log");
}),
);
});
describe("ignored path filtering", () => {
it.effect("filters ignored paths", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
yield* input.fixture.createRepo(cwd);
yield* input.fixture.ignorePath(cwd, "*.log");
const result = yield* driver.filterIgnoredPaths(cwd, [
"keep.ts",
"debug.log",
"nested/error.log",
]);
assert.deepStrictEqual(result, ["keep.ts"]);
}),
);
it.effect("returns empty input unchanged", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const driver = yield* VcsDriver;
yield* input.fixture.createRepo(cwd);
assert.deepStrictEqual(yield* driver.filterIgnoredPaths(cwd, []), []);
}),
);
});
});
}
@@ -5,8 +5,8 @@ import { it, afterEach, describe, expect, vi } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, PlatformError } from "effect";
import { ServerConfig } from "../../config.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
@@ -14,7 +14,8 @@ import { WorkspacePathsLive } from "./WorkspacePaths.ts";
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
Layer.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-workspace-entries-test-",
@@ -25,12 +26,11 @@ const TestLayer = Layer.empty.pipe(
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
const fileSystem = yield* FileSystem.FileSystem;
const gitCore = yield* GitCore;
const dir = yield* fileSystem.makeTempDirectoryScoped({
prefix: opts?.prefix ?? "t3code-workspace-entries-",
});
if (opts?.git) {
yield* gitCore.initRepo({ cwd: dir });
yield* git(dir, ["init"]);
}
return dir;
});
@@ -51,9 +51,10 @@ function writeTextFile(
const git = (cwd: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>
Effect.gen(function* () {
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
const process = yield* VcsProcess.VcsProcess;
const result = yield* process.run({
operation: "WorkspaceEntries.test.git",
command: "git",
cwd,
args,
...(env ? { env } : {}),
@@ -2,7 +2,7 @@ import * as OS from "node:os";
import fsPromises from "node:fs/promises";
import type { Dirent } from "node:fs";
import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect";
import { Cache, DateTime, Duration, Effect, Exit, Layer, Path } from "effect";
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";
@@ -13,7 +13,7 @@ import {
type RankedSearchResult,
} from "@t3tools/shared/searchRanking";
import { GitCore } from "../../git/Services/GitCore.ts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import {
WorkspaceEntries,
WorkspaceEntriesBrowseError,
@@ -174,38 +174,39 @@ const resolveBrowseTarget = (
export const makeWorkspaceEntries = Effect.gen(function* () {
const path = yield* Path.Path;
const gitOption = yield* Effect.serviceOption(GitCore);
const vcsRegistry = yield* VcsDriverRegistry;
const workspacePaths = yield* WorkspacePaths;
const isInsideGitWorkTree = (cwd: string): Effect.Effect<boolean> =>
Option.match(gitOption, {
onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
onNone: () => Effect.succeed(false),
});
const isInsideVcsWorkTree = (cwd: string): Effect.Effect<boolean> =>
vcsRegistry.detect({ cwd }).pipe(
Effect.map((handle) => handle !== null),
Effect.catch(() => Effect.succeed(false)),
);
const filterGitIgnoredPaths = (
const filterVcsIgnoredPaths = (
cwd: string,
relativePaths: string[],
): Effect.Effect<string[], never> =>
Option.match(gitOption, {
onSome: (git) =>
git.filterIgnoredPaths(cwd, relativePaths).pipe(
Effect.map((paths) => [...paths]),
Effect.catch(() => Effect.succeed(relativePaths)),
),
onNone: () => Effect.succeed(relativePaths),
});
vcsRegistry.detect({ cwd }).pipe(
Effect.flatMap((handle) =>
handle
? handle.driver.filterIgnoredPaths(cwd, relativePaths).pipe(
Effect.map((paths) => [...paths]),
Effect.catch(() => Effect.succeed(relativePaths)),
)
: Effect.succeed(relativePaths),
),
Effect.catch(() => Effect.succeed(relativePaths)),
);
const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")(
const buildWorkspaceIndexFromVcs = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromVcs")(
function* (cwd: string) {
if (Option.isNone(gitOption)) {
return null;
}
if (!(yield* isInsideGitWorkTree(cwd))) {
const vcs = yield* vcsRegistry.detect({ cwd }).pipe(Effect.catch(() => Effect.succeed(null)));
if (!vcs) {
return null;
}
const listedFiles = yield* gitOption.value
const listedFiles = yield* vcs.driver
.listWorkspaceFiles(cwd)
.pipe(Effect.catch(() => Effect.succeed(null)));
@@ -216,7 +217,10 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const listedPaths = [...listedFiles.paths]
.map((entry) => toPosixPath(entry))
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths);
const filePaths = yield* vcs.driver.filterIgnoredPaths(cwd, listedPaths).pipe(
Effect.map((paths) => [...paths]),
Effect.catch(() => filterVcsIgnoredPaths(cwd, listedPaths)),
);
const directorySet = new Set<string>();
for (const filePath of filePaths) {
@@ -248,9 +252,10 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
)
.map(toSearchableWorkspaceEntry);
const now = yield* DateTime.now;
const entries = [...directoryEntries, ...fileEntries];
return {
scannedAt: Date.now(),
scannedAt: now.epochMilliseconds,
entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
truncated: listedFiles.truncated || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
};
@@ -288,7 +293,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const buildWorkspaceIndexFromFilesystem = Effect.fn(
"WorkspaceEntries.buildWorkspaceIndexFromFilesystem",
)(function* (cwd: string): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd);
const shouldFilterWithGitIgnore = yield* isInsideVcsWorkTree(cwd);
let pendingDirectories: string[] = [""];
const entries: SearchableWorkspaceEntry[] = [];
@@ -336,7 +341,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
candidateEntries.map((entry) => entry.relativePath),
);
const allowedPathSet = shouldFilterWithGitIgnore
? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths))
? new Set(yield* filterVcsIgnoredPaths(cwd, candidatePaths))
: null;
for (const candidateEntries of candidateEntriesByDirectory) {
@@ -368,8 +373,9 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
}
}
const now = yield* DateTime.now;
return {
scannedAt: Date.now(),
scannedAt: now.epochMilliseconds,
entries,
truncated,
};
@@ -378,9 +384,9 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* (
cwd: string,
): Effect.fn.Return<WorkspaceIndex, WorkspaceEntriesError> {
const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd);
if (gitIndexed) {
return gitIndexed;
const vcsIndexed = yield* buildWorkspaceIndexFromVcs(cwd);
if (vcsIndexed) {
return vcsIndexed;
}
return yield* buildWorkspaceIndexFromFilesystem(cwd);
});
@@ -3,7 +3,8 @@ import { it, describe, expect } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { ServerConfig } from "../../config.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../../vcs/VcsProcess.ts";
import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts";
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
@@ -19,7 +20,7 @@ const TestLayer = Layer.empty.pipe(
Layer.provideMerge(ProjectLayer),
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
Layer.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-workspace-files-test-",
+53 -53
View File
@@ -29,9 +29,6 @@ import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery.ts";
import { ServerConfig } from "./config.ts";
import { GitCore } from "./git/Services/GitCore.ts";
import { GitManager } from "./git/Services/GitManager.ts";
import { GitStatusBroadcaster } from "./git/Services/GitStatusBroadcaster.ts";
import { Keybindings } from "./keybindings.ts";
import { Open, resolveAvailableEditors } from "./open.ts";
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
@@ -50,6 +47,8 @@ import { TerminalManager } from "./terminal/Services/Manager.ts";
import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts";
import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts";
import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePaths.ts";
import { VcsStatusBroadcaster } from "./vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "./git/GitWorkflowService.ts";
import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner.ts";
import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver.ts";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
@@ -136,9 +135,8 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const keybindings = yield* Keybindings;
const open = yield* Open;
const gitManager = yield* GitManager;
const git = yield* GitCore;
const gitStatusBroadcaster = yield* GitStatusBroadcaster;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const terminalManager = yield* TerminalManager;
const providerRegistry = yield* ProviderRegistry;
const config = yield* ServerConfig;
@@ -453,10 +451,10 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
}
if (bootstrap?.prepareWorktree) {
const worktree = yield* git.createWorktree({
const worktree = yield* gitWorkflow.createWorktree({
cwd: bootstrap.prepareWorktree.projectCwd,
branch: bootstrap.prepareWorktree.baseBranch,
newBranch: bootstrap.prepareWorktree.branch,
refName: bootstrap.prepareWorktree.baseBranch,
newRefName: bootstrap.prepareWorktree.branch,
path: null,
});
targetWorktreePath = worktree.worktree.path;
@@ -464,7 +462,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
type: "thread.meta.update",
commandId: serverCommandId("bootstrap-thread-meta-update"),
threadId: command.threadId,
branch: worktree.worktree.branch,
branch: worktree.worktree.refName,
worktreePath: targetWorktreePath,
});
yield* refreshGitStatus(targetWorktreePath);
@@ -540,7 +538,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
});
const refreshGitStatus = (cwd: string) =>
gitStatusBroadcaster
vcsStatusBroadcaster
.refreshStatus(cwd)
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);
@@ -831,26 +829,26 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
),
{ "rpc.aggregate": "workspace" },
),
[WS_METHODS.subscribeGitStatus]: (input) =>
[WS_METHODS.subscribeVcsStatus]: (input) =>
observeRpcStream(
WS_METHODS.subscribeGitStatus,
gitStatusBroadcaster.streamStatus(input),
WS_METHODS.subscribeVcsStatus,
vcsStatusBroadcaster.streamStatus(input),
{
"rpc.aggregate": "git",
"rpc.aggregate": "vcs",
},
),
[WS_METHODS.gitRefreshStatus]: (input) =>
[WS_METHODS.vcsRefreshStatus]: (input) =>
observeRpcEffect(
WS_METHODS.gitRefreshStatus,
gitStatusBroadcaster.refreshStatus(input.cwd),
WS_METHODS.vcsRefreshStatus,
vcsStatusBroadcaster.refreshStatus(input.cwd),
{
"rpc.aggregate": "git",
"rpc.aggregate": "vcs",
},
),
[WS_METHODS.gitPull]: (input) =>
[WS_METHODS.vcsPull]: (input) =>
observeRpcEffect(
WS_METHODS.gitPull,
git.pullCurrentBranch(input.cwd).pipe(
WS_METHODS.vcsPull,
gitWorkflow.pullCurrentBranch(input.cwd).pipe(
Effect.matchCauseEffect({
onFailure: (cause) => Effect.failCause(cause),
onSuccess: (result) =>
@@ -863,7 +861,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
observeRpcStream(
WS_METHODS.gitRunStackedAction,
Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>
gitManager
gitWorkflow
.runStackedAction(input, {
actionId: input.actionId,
progressReporter: {
@@ -880,55 +878,57 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
}),
),
),
{ "rpc.aggregate": "git" },
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.gitResolvePullRequest]: (input) =>
observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), {
"rpc.aggregate": "git",
}),
observeRpcEffect(
WS_METHODS.gitResolvePullRequest,
gitWorkflow.resolvePullRequest(input),
{
"rpc.aggregate": "git",
},
),
[WS_METHODS.gitPreparePullRequestThread]: (input) =>
observeRpcEffect(
WS_METHODS.gitPreparePullRequestThread,
gitManager
gitWorkflow
.preparePullRequestThread(input)
.pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
),
[WS_METHODS.gitListBranches]: (input) =>
observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), {
"rpc.aggregate": "git",
[WS_METHODS.vcsListRefs]: (input) =>
observeRpcEffect(WS_METHODS.vcsListRefs, gitWorkflow.listRefs(input), {
"rpc.aggregate": "vcs",
}),
[WS_METHODS.gitCreateWorktree]: (input) =>
[WS_METHODS.vcsCreateWorktree]: (input) =>
observeRpcEffect(
WS_METHODS.gitCreateWorktree,
git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
WS_METHODS.vcsCreateWorktree,
gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.gitRemoveWorktree]: (input) =>
[WS_METHODS.vcsRemoveWorktree]: (input) =>
observeRpcEffect(
WS_METHODS.gitRemoveWorktree,
git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
WS_METHODS.vcsRemoveWorktree,
gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.gitCreateBranch]: (input) =>
[WS_METHODS.vcsCreateRef]: (input) =>
observeRpcEffect(
WS_METHODS.gitCreateBranch,
git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
WS_METHODS.vcsCreateRef,
gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.gitCheckout]: (input) =>
[WS_METHODS.vcsSwitchRef]: (input) =>
observeRpcEffect(
WS_METHODS.gitCheckout,
Effect.scoped(git.checkoutBranch(input)).pipe(
Effect.tap(() => refreshGitStatus(input.cwd)),
),
{ "rpc.aggregate": "git" },
WS_METHODS.vcsSwitchRef,
gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.gitInit]: (input) =>
[WS_METHODS.vcsInit]: (input) =>
observeRpcEffect(
WS_METHODS.gitInit,
git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "git" },
WS_METHODS.vcsInit,
gitWorkflow.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),
{ "rpc.aggregate": "vcs" },
),
[WS_METHODS.terminalOpen]: (input) =>
observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {
@@ -1,4 +1,4 @@
import { EnvironmentId, type GitBranch } from "@t3tools/contracts";
import { EnvironmentId, type VcsRef } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
@@ -28,7 +28,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
).toBe("local");
});
it("keeps new-worktree mode when selecting a base branch before worktree creation", () => {
it("keeps new-worktree mode when selecting a base ref before worktree creation", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: null,
@@ -38,7 +38,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
).toBe("worktree");
});
it("uses worktree mode when selecting a branch already attached to a worktree", () => {
it("uses worktree mode when selecting a ref already attached to a worktree", () => {
expect(
resolveDraftEnvModeAfterBranchChange({
nextWorktreePath: "/repo/.t3/worktrees/feature-a",
@@ -50,7 +50,7 @@ describe("resolveDraftEnvModeAfterBranchChange", () => {
});
describe("resolveBranchToolbarValue", () => {
it("defaults new-worktree mode to current git branch when no explicit base branch is set", () => {
it("defaults new-worktree mode to current git ref when no explicit base ref is set", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
@@ -61,7 +61,7 @@ describe("resolveBranchToolbarValue", () => {
).toBe("main");
});
it("keeps an explicitly selected worktree base branch", () => {
it("keeps an explicitly selected worktree base ref", () => {
expect(
resolveBranchToolbarValue({
envMode: "worktree",
@@ -72,7 +72,7 @@ describe("resolveBranchToolbarValue", () => {
).toBe("feature/base");
});
it("shows the actual checked-out branch when not selecting a new worktree base", () => {
it("shows the actual checked-out ref when not selecting a new worktree base", () => {
expect(
resolveBranchToolbarValue({
envMode: "local",
@@ -186,8 +186,8 @@ describe("deriveLocalBranchNameFromRemoteRef", () => {
});
describe("dedupeRemoteBranchesWithLocalMatches", () => {
it("hides remote refs when the matching local branch exists", () => {
const input: GitBranch[] = [
it("hides remote refs when the matching local ref exists", () => {
const input: VcsRef[] = [
{
name: "feature/demo",
current: false,
@@ -212,14 +212,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
});
it("keeps all entries when no local match exists for a remote ref", () => {
const input: GitBranch[] = [
const input: VcsRef[] = [
{
name: "feature/local",
current: false,
@@ -236,14 +236,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
"feature/local",
"origin/feature/remote-only",
]);
});
it("keeps non-origin remote refs visible even when a matching local branch exists", () => {
const input: GitBranch[] = [
it("keeps non-origin remote refs visible even when a matching local ref exists", () => {
const input: VcsRef[] = [
{
name: "feature/demo",
current: false,
@@ -260,14 +260,14 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
"feature/demo",
"my-org/upstream/feature/demo",
]);
});
it("keeps non-origin remote refs visible when git tracks with first-slash local naming", () => {
const input: GitBranch[] = [
const input: VcsRef[] = [
{
name: "upstream/feature",
current: false,
@@ -284,7 +284,7 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
},
];
expect(dedupeRemoteBranchesWithLocalMatches(input).map((branch) => branch.name)).toEqual([
expect(dedupeRemoteBranchesWithLocalMatches(input).map((ref) => ref.name)).toEqual([
"upstream/feature",
"my-org/upstream/feature",
]);
@@ -292,12 +292,12 @@ describe("dedupeRemoteBranchesWithLocalMatches", () => {
});
describe("resolveBranchSelectionTarget", () => {
it("reuses an existing secondary worktree for the selected branch", () => {
it("reuses an existing secondary worktree for the selected ref", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
refName: {
isDefault: false,
worktreePath: "/repo/.t3/worktrees/feature-b",
},
@@ -309,12 +309,12 @@ describe("resolveBranchSelectionTarget", () => {
});
});
it("switches back to the main repo when the branch already lives there", () => {
it("switches back to the main repo when the ref already lives there", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
refName: {
isDefault: true,
worktreePath: "/repo",
},
@@ -326,12 +326,12 @@ describe("resolveBranchSelectionTarget", () => {
});
});
it("checks out the default branch in the main repo when leaving a secondary worktree", () => {
it("checks out the default ref in the main repo when leaving a secondary worktree", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
refName: {
isDefault: true,
worktreePath: null,
},
@@ -343,12 +343,12 @@ describe("resolveBranchSelectionTarget", () => {
});
});
it("keeps checkout in the current worktree for non-default branches", () => {
it("keeps checkout in the current worktree for non-default refs", () => {
expect(
resolveBranchSelectionTarget({
activeProjectCwd: "/repo",
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
branch: {
refName: {
isDefault: false,
worktreePath: null,
},
@@ -373,7 +373,7 @@ describe("shouldIncludeBranchPickerItem", () => {
).toBe(true);
});
it("keeps the synthetic create-branch item visible for arbitrary branch input", () => {
it("keeps the synthetic create-ref item visible for arbitrary ref input", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "__create_new_branch__:feature/demo",
@@ -384,7 +384,7 @@ describe("shouldIncludeBranchPickerItem", () => {
).toBe(true);
});
it("still filters ordinary branch items by query text", () => {
it("still filters ordinary ref items by query text", () => {
expect(
shouldIncludeBranchPickerItem({
itemValue: "main",
@@ -1,4 +1,4 @@
import type { EnvironmentId, GitBranch, ProjectId } from "@t3tools/contracts";
import type { EnvironmentId, VcsRef, ProjectId } from "@t3tools/contracts";
import { Schema } from "effect";
export {
dedupeRemoteBranchesWithLocalMatches,
@@ -100,24 +100,24 @@ export function resolveBranchToolbarValue(input: {
export function resolveBranchSelectionTarget(input: {
activeProjectCwd: string;
activeWorktreePath: string | null;
branch: Pick<GitBranch, "isDefault" | "worktreePath">;
refName: Pick<VcsRef, "isDefault" | "worktreePath">;
}): {
checkoutCwd: string;
nextWorktreePath: string | null;
reuseExistingWorktree: boolean;
} {
const { activeProjectCwd, activeWorktreePath, branch } = input;
const { activeProjectCwd, activeWorktreePath, refName } = input;
if (branch.worktreePath) {
if (refName.worktreePath) {
return {
checkoutCwd: branch.worktreePath,
nextWorktreePath: branch.worktreePath === activeProjectCwd ? null : branch.worktreePath,
checkoutCwd: refName.worktreePath,
nextWorktreePath: refName.worktreePath === activeProjectCwd ? null : refName.worktreePath,
reuseExistingWorktree: true,
};
}
const nextWorktreePath =
activeWorktreePath !== null && branch.isDefault ? null : activeWorktreePath;
activeWorktreePath !== null && refName.isDefault ? null : activeWorktreePath;
return {
checkoutCwd: nextWorktreePath ?? activeProjectCwd,
@@ -1,5 +1,5 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts";
import type { EnvironmentId, VcsRef, ThreadId } from "@t3tools/contracts";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { ChevronDownIcon } from "lucide-react";
@@ -23,6 +23,7 @@ import { cn } from "../lib/utils";
import { parsePullRequestReference } from "../pullRequestReference";
import { useStore } from "../store";
import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors";
import { resolveVcsTerms } from "../vcsPresentation";
import {
deriveLocalBranchNameFromRemoteRef,
resolveBranchSelectionTarget,
@@ -53,7 +54,7 @@ interface BranchToolbarBranchSelectorProps {
envLocked: boolean;
effectiveEnvModeOverride?: "local" | "worktree";
activeThreadBranchOverride?: string | null;
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
onActiveThreadBranchOverrideChange?: (refName: string | null) => void;
onCheckoutPullRequestRequest?: (reference: string) => void;
onComposerFocusRequest?: () => void;
}
@@ -66,10 +67,11 @@ function getBranchTriggerLabel(input: {
activeWorktreePath: string | null;
effectiveEnvMode: "local" | "worktree";
resolvedActiveBranch: string | null;
refNoun: string;
}): string {
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch, refNoun } = input;
if (!resolvedActiveBranch) {
return "Select branch";
return `Select ${refNoun}`;
}
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
return `From ${resolvedActiveBranch}`;
@@ -193,7 +195,7 @@ export function BranchToolbarBranchSelector({
);
// ---------------------------------------------------------------------------
// Git branch queries
// Git ref queries
// ---------------------------------------------------------------------------
const queryClient = useQueryClient();
const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false);
@@ -201,6 +203,7 @@ export function BranchToolbarBranchSelector({
const deferredBranchQuery = useDeferredValue(branchQuery);
const branchStatusQuery = useGitStatus({ environmentId, cwd: branchCwd });
const vcsTerms = resolveVcsTerms(branchStatusQuery.data?.kind);
const trimmedBranchQuery = branchQuery.trim();
const deferredTrimmedBranchQuery = deferredBranchQuery.trim();
@@ -224,22 +227,22 @@ export function BranchToolbarBranchSelector({
query: deferredTrimmedBranchQuery,
}),
);
const branches = useMemo(
() => branchesSearchData?.pages.flatMap((page) => page.branches) ?? [],
const refs = useMemo(
() => branchesSearchData?.pages.flatMap((page) => page.refs) ?? [],
[branchesSearchData?.pages],
);
const currentGitBranch =
branchStatusQuery.data?.branch ?? branches.find((branch) => branch.current)?.name ?? null;
branchStatusQuery.data?.refName ?? refs.find((refName) => refName.current)?.name ?? null;
const canonicalActiveBranch = resolveBranchToolbarValue({
envMode: effectiveEnvMode,
activeWorktreePath,
activeThreadBranch,
currentGitBranch,
});
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
const branchNames = useMemo(() => refs.map((refName) => refName.name), [refs]);
const branchByName = useMemo(
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
[branches],
() => new Map(refs.map((refName) => [refName.name, refName] as const)),
[refs],
);
const normalizedDeferredBranchQuery = deferredTrimmedBranchQuery.toLowerCase();
const prReference = parsePullRequestReference(trimmedBranchQuery);
@@ -289,11 +292,11 @@ export function BranchToolbarBranchSelector({
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
const branchStatusText = isBranchesSearchPending
? "Loading branches..."
? `Loading ${vcsTerms.refNounPlural}...`
: isFetchingNextPage
? "Loading more branches..."
? `Loading more ${vcsTerms.refNounPlural}...`
: hasNextPage
? `Showing ${branches.length} of ${totalBranchCount} branches`
? `Showing ${refs.length} of ${totalBranchCount} ${vcsTerms.refNounPlural}`
: null;
// ---------------------------------------------------------------------------
@@ -303,17 +306,17 @@ export function BranchToolbarBranchSelector({
startBranchActionTransition(async () => {
await action().catch(() => undefined);
await queryClient
.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, branchCwd) })
.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, branchCwd) })
.catch(() => undefined);
});
};
const selectBranch = (branch: GitBranch) => {
const selectBranch = (refName: VcsRef) => {
const api = readEnvironmentApi(environmentId);
if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
if (isSelectingWorktreeBase) {
setThreadBranch(branch.name, null);
setThreadBranch(refName.name, null);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
@@ -322,19 +325,19 @@ export function BranchToolbarBranchSelector({
const selectionTarget = resolveBranchSelectionTarget({
activeProjectCwd,
activeWorktreePath,
branch,
refName,
});
if (selectionTarget.reuseExistingWorktree) {
setThreadBranch(branch.name, selectionTarget.nextWorktreePath);
setThreadBranch(refName.name, selectionTarget.nextWorktreePath);
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
return;
}
const selectedBranchName = branch.isRemote
? deriveLocalBranchNameFromRemoteRef(branch.name)
: branch.name;
const selectedBranchName = refName.isRemote
? deriveLocalBranchNameFromRemoteRef(refName.name)
: refName.name;
setIsBranchMenuOpen(false);
onComposerFocusRequest?.();
@@ -343,12 +346,12 @@ export function BranchToolbarBranchSelector({
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(selectedBranchName);
try {
const checkoutResult = await api.git.checkout({
const checkoutResult = await api.vcs.switchRef({
cwd: selectionTarget.checkoutCwd,
branch: branch.name,
refName: refName.name,
});
const nextBranchName = branch.isRemote
? (checkoutResult.branch ?? selectedBranchName)
const nextBranchName = refName.isRemote
? (checkoutResult.refName ?? selectedBranchName)
: selectedBranchName;
setOptimisticBranch(nextBranchName);
setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath);
@@ -357,7 +360,7 @@ export function BranchToolbarBranchSelector({
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to checkout branch.",
title: `Failed to switch ${vcsTerms.refNoun}.`,
description: toBranchActionErrorMessage(error),
}),
);
@@ -365,7 +368,7 @@ export function BranchToolbarBranchSelector({
});
};
const createBranch = (rawName: string) => {
const createRef = (rawName: string) => {
const name = rawName.trim();
const api = readEnvironmentApi(environmentId);
if (!api || !branchCwd || !name || isBranchActionPending) return;
@@ -377,19 +380,19 @@ export function BranchToolbarBranchSelector({
const previousBranch = resolvedActiveBranch;
setOptimisticBranch(name);
try {
const createBranchResult = await api.git.createBranch({
const createBranchResult = await api.vcs.createRef({
cwd: branchCwd,
branch: name,
checkout: true,
refName: name,
switchRef: true,
});
setOptimisticBranch(createBranchResult.branch);
setThreadBranch(createBranchResult.branch, activeWorktreePath);
setOptimisticBranch(createBranchResult.refName);
setThreadBranch(createBranchResult.refName, activeWorktreePath);
} catch (error) {
setOptimisticBranch(previousBranch);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to create and checkout branch.",
title: `Failed to create and switch ${vcsTerms.refNoun}.`,
description: toBranchActionErrorMessage(error),
}),
);
@@ -420,7 +423,7 @@ export function BranchToolbarBranchSelector({
return;
}
void queryClient.invalidateQueries({
queryKey: gitQueryKeys.branches(environmentId, branchCwd),
queryKey: gitQueryKeys.refs(environmentId, branchCwd),
});
},
[branchCwd, environmentId, queryClient],
@@ -482,12 +485,13 @@ export function BranchToolbarBranchSelector({
useEffect(() => {
if (shouldVirtualizeBranchList) return;
maybeFetchNextBranchPage();
}, [branches.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
}, [refs.length, maybeFetchNextBranchPage, shouldVirtualizeBranchList]);
const triggerLabel = getBranchTriggerLabel({
activeWorktreePath,
effectiveEnvMode,
resolvedActiveBranch,
refNoun: vcsTerms.refNoun,
});
function renderPickerItem(itemValue: string, index: number) {
@@ -522,25 +526,27 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
onClick={() => createBranch(trimmedBranchQuery)}
onClick={() => createRef(trimmedBranchQuery)}
>
<span className="truncate">Create new branch &quot;{trimmedBranchQuery}&quot;</span>
<span className="truncate">
Create new {vcsTerms.refNoun} &quot;{trimmedBranchQuery}&quot;
</span>
</ComboboxItem>
);
}
const branch = branchByName.get(itemValue);
if (!branch) return null;
const refName = branchByName.get(itemValue);
if (!refName) return null;
const hasSecondaryWorktree =
branch.worktreePath && activeProjectCwd && branch.worktreePath !== activeProjectCwd;
const badge = branch.current
refName.worktreePath && activeProjectCwd && refName.worktreePath !== activeProjectCwd;
const badge = refName.current
? "current"
: hasSecondaryWorktree
? "worktree"
: branch.isRemote
: refName.isRemote
? "remote"
: branch.isDefault
: refName.isDefault
? "default"
: null;
return (
@@ -549,7 +555,7 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
onClick={() => selectBranch(branch)}
onClick={() => selectBranch(refName)}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="truncate">{itemValue}</span>
@@ -581,7 +587,7 @@ export function BranchToolbarBranchSelector({
<ComboboxTrigger
render={<Button variant="ghost" size="xs" />}
className={cn("min-w-0 text-muted-foreground/70 hover:text-foreground/80", className)}
disabled={(isBranchesSearchPending && branches.length === 0) || isBranchActionPending}
disabled={(isBranchesSearchPending && refs.length === 0) || isBranchActionPending}
>
<span className="min-w-0 max-w-[240px] truncate">{triggerLabel}</span>
<ChevronDownIcon className="shrink-0" />
@@ -591,14 +597,14 @@ export function BranchToolbarBranchSelector({
<ComboboxInput
className="[&_input]:font-sans rounded-md"
inputClassName="ring-0"
placeholder="Search branches..."
placeholder="Search refs..."
showTrigger={false}
size="sm"
value={branchQuery}
onChange={(event) => setBranchQuery(event.target.value)}
/>
</div>
<ComboboxEmpty>No branches found.</ComboboxEmpty>
<ComboboxEmpty>No refs found.</ComboboxEmpty>
{shouldVirtualizeBranchList ? (
<ComboboxListVirtualized>
+25 -24
View File
@@ -206,6 +206,7 @@ function createMockEnvironmentApi(input: {
filesystem: {
browse: input.browse,
},
vcs: {} as EnvironmentApi["vcs"],
git: {} as EnvironmentApi["git"],
orchestration: {
dispatchCommand: input.dispatchCommand,
@@ -951,13 +952,13 @@ function resolveWsRpc(body: NormalizedWsRpcRequestBody): unknown {
if (tag === WS_METHODS.serverGetConfig) {
return fixture.serverConfig;
}
if (tag === WS_METHODS.gitListBranches) {
if (tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 1,
branches: [
refs: [
{
name: "main",
current: true,
@@ -2287,11 +2288,11 @@ describe("ChatView timeline estimator parity (full app)", () => {
branchButton.click();
const branchInput = await waitForElement(
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
"Unable to find branch search input.",
() => document.querySelector<HTMLInputElement>('input[placeholder="Search refs..."]'),
"Unable to find ref search input.",
);
branchInput.focus();
await page.getByPlaceholder("Search branches...").fill("1359");
await page.getByPlaceholder("Search refs...").fill("1359");
const checkoutItem = await waitForElement(
() =>
@@ -2425,7 +2426,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
{ timeout: 8_000, interval: 16 },
);
expect(wsRequests.some((request) => request._tag === WS_METHODS.gitCreateWorktree)).toBe(
expect(wsRequests.some((request) => request._tag === WS_METHODS.vcsCreateWorktree)).toBe(
false,
);
expect(
@@ -2572,13 +2573,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
),
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.gitListBranches) {
if (body._tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 1,
branches: [
refs: [
{
name: "main",
current: true,
@@ -2665,13 +2666,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
),
},
resolveRpc: (body) => {
if (body._tag === WS_METHODS.gitListBranches) {
if (body._tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 2,
branches: [
refs: [
{
name: "main",
current: true,
@@ -2761,13 +2762,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
viewport: DEFAULT_VIEWPORT,
snapshot: snapshotWithTwoThreads,
resolveRpc: (body) => {
if (body._tag === WS_METHODS.gitListBranches) {
if (body._tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 2,
branches: [
refs: [
{
name: "main",
current: true,
@@ -3021,13 +3022,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
snapshot: createDraftOnlySnapshot(),
initialPath: `/draft/${activeDraftId}`,
resolveRpc: (body) => {
if (body._tag === WS_METHODS.gitListBranches) {
if (body._tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 2,
branches: [
refs: [
{
name: "main",
current: true,
@@ -3146,13 +3147,13 @@ describe("ChatView timeline estimator parity (full app)", () => {
snapshot: createDraftOnlySnapshot(),
initialPath: `/draft/${draftId}`,
resolveRpc: (body) => {
if (body._tag === WS_METHODS.gitListBranches) {
if (body._tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: branches.length,
branches,
refs: branches,
};
}
return undefined;
@@ -3170,8 +3171,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
branchButton.click();
await waitForElement(
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
"Unable to find branch search input.",
() => document.querySelector<HTMLInputElement>('input[placeholder="Search refs..."]'),
"Unable to find ref search input.",
);
const popup = await waitForElement(
+7 -5
View File
@@ -1458,7 +1458,8 @@ export default function ChatView(props: ChatViewProps) {
? terminalLaunchContext
: (storeServerTerminalLaunchContext ?? null);
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const vcsKind = gitStatusQuery.data?.kind ?? null;
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -2136,7 +2137,7 @@ export default function ChatView(props: ChatViewProps) {
: (activeThread?.branch ?? null);
const sendEnvMode = resolveSendEnvMode({
requestedEnvMode: envMode,
isGitRepo,
isGitRepo: isVcsRepo,
});
useEffect(() => {
@@ -3297,7 +3298,8 @@ export default function ChatView(props: ChatViewProps) {
{...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title}
activeProjectName={activeProject?.name}
isGitRepo={isGitRepo}
isVcsRepo={isVcsRepo}
vcsKind={vcsKind}
openInCwd={gitCwd}
activeProjectScripts={activeProject?.scripts}
preferredScriptId={
@@ -3377,7 +3379,7 @@ export default function ChatView(props: ChatViewProps) {
<div
className={cn(
"pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] pt-1.5 sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)] sm:pt-2",
isGitRepo
isVcsRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
@@ -3450,7 +3452,7 @@ export default function ChatView(props: ChatViewProps) {
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
{isGitRepo && (
{isVcsRepo && (
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
+6 -4
View File
@@ -35,6 +35,7 @@ import { createThreadSelectorByRef } from "../storeSelectors";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import { useSettings } from "../hooks/useSettings";
import { formatShortTimestamp } from "../timestampFormat";
import { resolveVcsTerms } from "../vcsPresentation";
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
@@ -201,7 +202,8 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
environmentId: activeThread?.environmentId ?? null,
cwd: activeCwd ?? null,
});
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const isVcsRepo = gitStatusQuery.data?.isRepo ?? true;
const vcsTerms = resolveVcsTerms(gitStatusQuery.data?.kind);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const orderedTurnDiffSummaries = useMemo(
@@ -278,7 +280,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
fromTurnCount: activeCheckpointRange?.fromTurnCount ?? null,
toTurnCount: activeCheckpointRange?.toTurnCount ?? null,
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : conversationCacheScope,
enabled: isGitRepo,
enabled: isVcsRepo,
}),
);
const selectedTurnCheckpointDiff = selectedTurn
@@ -561,9 +563,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Select a thread to inspect turn diffs.
</div>
) : !isGitRepo ? (
) : !isVcsRepo ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
Turn diffs are unavailable because this project is not a git repository.
Turn diffs are unavailable because this project is not a {vcsTerms.repositoryNoun}.
</div>
) : orderedTurnDiffSummaries.length === 0 ? (
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
@@ -113,7 +113,16 @@ vi.mock("~/lib/gitStatusState", () => ({
resetGitStatusStateForTests: () => undefined,
useGitStatus: vi.fn(() => ({
data: {
branch: BRANCH_NAME,
kind: "git",
isRepo: true,
sourceControlProvider: {
kind: "github",
name: "GitHub",
baseUrl: "https://github.com",
},
hasPrimaryRemote: true,
isDefaultRef: false,
refName: BRANCH_NAME,
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
@@ -1,4 +1,4 @@
import type { GitStatusResult } from "@t3tools/contracts";
import type { VcsStatusResult } from "@t3tools/contracts";
import { assert, describe, it } from "vitest";
import {
buildGitActionProgressStages,
@@ -11,12 +11,13 @@ import {
resolveThreadBranchUpdate,
} from "./GitActionsControl.logic";
function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
function status(overrides: Partial<VcsStatusResult> = {}): VcsStatusResult {
return {
kind: "git",
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/test",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/test",
hasWorkingTreeChanges: false,
workingTree: {
files: [],
@@ -31,7 +32,7 @@ function status(overrides: Partial<GitStatusResult> = {}): GitStatusResult {
};
}
describe("when: branch is clean and has an open PR", () => {
describe("when: ref is clean and has an open PR", () => {
it("resolveQuickAction opens the existing PR", () => {
const quick = resolveQuickAction(
status({
@@ -39,8 +40,8 @@ describe("when: branch is clean and has an open PR", () => {
number: 10,
title: "Open PR",
url: "https://example.com/pr/10",
baseBranch: "main",
headBranch: "feature/test",
baseRef: "main",
headRef: "feature/test",
state: "open",
},
}),
@@ -56,8 +57,8 @@ describe("when: branch is clean and has an open PR", () => {
number: 11,
title: "Existing PR",
url: "https://example.com/pr/11",
baseBranch: "main",
headBranch: "feature/test",
baseRef: "main",
headRef: "feature/test",
state: "open",
},
}),
@@ -150,7 +151,7 @@ describe("when: git status is unavailable", () => {
});
});
describe("when: branch is clean, ahead, and has an open PR", () => {
describe("when: ref is clean, ahead, and has an open PR", () => {
it("resolveQuickAction prefers push", () => {
const quick = resolveQuickAction(
status({
@@ -159,8 +160,8 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
number: 13,
title: "Open PR",
url: "https://example.com/pr/13",
baseBranch: "main",
headBranch: "feature/test",
baseRef: "main",
headRef: "feature/test",
state: "open",
},
}),
@@ -177,8 +178,8 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
number: 12,
title: "Existing PR",
url: "https://example.com/pr/12",
baseBranch: "main",
headBranch: "feature/test",
baseRef: "main",
headRef: "feature/test",
state: "open",
},
}),
@@ -212,7 +213,7 @@ describe("when: branch is clean, ahead, and has an open PR", () => {
});
});
describe("when: branch is clean, ahead, and has no open PR", () => {
describe("when: ref is clean, ahead, and has no open PR", () => {
it("resolveQuickAction pushes and creates a PR", () => {
const quick = resolveQuickAction(status({ aheadCount: 2, pr: null }), false);
assert.deepInclude(quick, {
@@ -253,7 +254,7 @@ describe("when: branch is clean, ahead, and has no open PR", () => {
});
});
describe("when: branch is clean, up to date, and has no open PR", () => {
describe("when: ref is clean, up to date, and has no open PR", () => {
it("resolveQuickAction returns disabled no-action state", () => {
const quick = resolveQuickAction(
status({ aheadCount: 0, behindCount: 0, hasWorkingTreeChanges: false, pr: null }),
@@ -293,7 +294,7 @@ describe("when: branch is clean, up to date, and has no open PR", () => {
});
});
describe("when: branch is behind upstream", () => {
describe("when: ref is behind upstream", () => {
it("resolveQuickAction returns pull", () => {
const quick = resolveQuickAction(status({ behindCount: 2 }), false);
assert.deepInclude(quick, { kind: "run_pull", label: "Pull", disabled: false });
@@ -330,11 +331,11 @@ describe("when: branch is behind upstream", () => {
});
});
describe("when: branch has diverged from upstream", () => {
describe("when: ref has diverged from upstream", () => {
it("resolveQuickAction returns a disabled sync hint", () => {
const quick = resolveQuickAction(status({ aheadCount: 2, behindCount: 1 }), false);
assert.deepEqual(quick, {
label: "Sync branch",
label: "Sync ref",
disabled: true,
kind: "show_hint",
hint: "Branch has diverged from upstream. Rebase/merge first.",
@@ -375,8 +376,8 @@ describe("when: working tree has local changes", () => {
number: 16,
title: "Existing PR",
url: "https://example.com/pr/16",
baseBranch: "main",
headBranch: "feature/test",
baseRef: "main",
headRef: "feature/test",
state: "open",
},
}),
@@ -420,10 +421,10 @@ describe("when: working tree has local changes", () => {
});
});
describe("when: on default branch without open PR", () => {
describe("when: on default ref without open PR", () => {
it("resolveQuickAction returns commit and push when local changes exist", () => {
const quick = resolveQuickAction(
status({ branch: "main", hasWorkingTreeChanges: true }),
status({ refName: "main", hasWorkingTreeChanges: true }),
false,
true,
);
@@ -435,9 +436,9 @@ describe("when: on default branch without open PR", () => {
});
});
it("resolveQuickAction returns push when branch is ahead", () => {
it("resolveQuickAction returns push when ref is ahead", () => {
const quick = resolveQuickAction(
status({ branch: "main", aheadCount: 2, pr: null }),
status({ refName: "main", aheadCount: 2, pr: null }),
false,
true,
);
@@ -450,7 +451,7 @@ describe("when: on default branch without open PR", () => {
});
});
describe("when: working tree has local changes and branch is behind upstream", () => {
describe("when: working tree has local changes and ref is behind upstream", () => {
it("resolveQuickAction still prefers commit, push, and create PR", () => {
const quick = resolveQuickAction(
status({ hasWorkingTreeChanges: true, behindCount: 1 }),
@@ -497,14 +498,14 @@ describe("when: working tree has local changes and branch is behind upstream", (
describe("when: HEAD is detached and there are no local changes", () => {
it("resolveQuickAction shows detached head hint", () => {
const quick = resolveQuickAction(
status({ branch: null, hasWorkingTreeChanges: false, hasUpstream: false }),
status({ refName: null, hasWorkingTreeChanges: false, hasUpstream: false }),
false,
);
assert.deepInclude(quick, { kind: "show_hint", label: "Commit", disabled: true });
});
it("buildMenuItems keeps commit, push, and PR disabled", () => {
const items = buildMenuItems(status({ branch: null, hasWorkingTreeChanges: false }), false);
const items = buildMenuItems(status({ refName: null, hasWorkingTreeChanges: false }), false);
assert.deepEqual(items, [
{
id: "commit",
@@ -534,7 +535,7 @@ describe("when: HEAD is detached and there are no local changes", () => {
});
});
describe("when: branch has no upstream configured", () => {
describe("when: ref has no upstream configured", () => {
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
const quick = resolveQuickAction(
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
@@ -557,8 +558,8 @@ describe("when: branch has no upstream configured", () => {
number: 14,
title: "Existing PR",
url: "https://example.com/pr/14",
baseBranch: "main",
headBranch: "feature/test",
baseRef: "main",
headRef: "feature/test",
state: "open",
},
}),
@@ -580,8 +581,8 @@ describe("when: branch has no upstream configured", () => {
number: 15,
title: "Existing PR",
url: "https://example.com/pr/15",
baseBranch: "main",
headBranch: "feature/test",
baseRef: "main",
headRef: "feature/test",
state: "open",
},
}),
@@ -725,10 +726,10 @@ describe("when: branch has no upstream configured", () => {
]);
});
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
it("resolveQuickAction is disabled on default ref when no upstream exists and no commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
refName: "main",
hasUpstream: false,
aheadCount: 0,
pr: null,
@@ -744,10 +745,10 @@ describe("when: branch has no upstream configured", () => {
});
});
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
it("resolveQuickAction uses push-only on default ref when no upstream exists and commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
refName: "main",
hasUpstream: false,
aheadCount: 1,
pr: null,
@@ -763,7 +764,7 @@ describe("when: branch has no upstream configured", () => {
});
});
it("buildMenuItems still disables push and create PR when branch is behind", () => {
it("buildMenuItems still disables push and create PR when ref is behind", () => {
const items = buildMenuItems(
status({
hasUpstream: false,
@@ -803,7 +804,7 @@ describe("when: branch has no upstream configured", () => {
});
describe("requiresDefaultBranchConfirmation", () => {
it("requires confirmation for push actions on default branch", () => {
it("requires confirmation for push actions on default ref", () => {
assert.isFalse(requiresDefaultBranchConfirmation("commit", true));
assert.isTrue(requiresDefaultBranchConfirmation("push", true));
assert.isTrue(requiresDefaultBranchConfirmation("create_pr", true));
@@ -823,9 +824,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
});
assert.deepEqual(copy, {
title: "Push to default branch?",
title: "Push to default ref?",
description:
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
'This action will push local commits on "main". You can continue on this ref or create a feature ref and run the same action there.',
continueLabel: "Push to main",
});
});
@@ -838,9 +839,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
});
assert.deepEqual(copy, {
title: "Push & create PR from default branch?",
title: "Push & create PR from default ref?",
description:
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
'This action will push local commits and create a PR on "main". You can continue on this ref or create a feature ref and run the same action there.',
continueLabel: "Push & create PR",
});
});
@@ -853,9 +854,9 @@ describe("resolveDefaultBranchActionDialogCopy", () => {
});
assert.deepEqual(copy, {
title: "Commit, push & create PR from default branch?",
title: "Commit, push & create PR from default ref?",
description:
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
'This action will commit, push, and create a PR on "main". You can continue on this ref or create a feature ref and run the same action there.',
continueLabel: "Commit, push & create PR",
});
});
@@ -944,7 +945,7 @@ describe("resolveThreadBranchUpdate", () => {
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
subject: "feat: add ref sync",
},
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
@@ -968,7 +969,7 @@ describe("resolveThreadBranchUpdate", () => {
commit: {
status: "created",
commitSha: "89abcdef01234567",
subject: "feat: add branch sync",
subject: "feat: add ref sync",
},
push: { status: "pushed", branch: "feature/fix-toast-copy" },
pr: { status: "skipped_not_requested" },
@@ -985,8 +986,8 @@ describe("resolveThreadBranchUpdate", () => {
describe("resolveLiveThreadBranchUpdate", () => {
it("returns a branch update when live git status differs from stored thread metadata", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "feature/old-branch",
gitStatus: status({ branch: "effect-atom" }),
threadBranch: "feature/old-ref",
gitStatus: status({ refName: "effect-atom" }),
});
assert.deepEqual(update, {
@@ -996,35 +997,35 @@ describe("resolveLiveThreadBranchUpdate", () => {
it("returns null when live git status is unavailable", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "feature/old-branch",
threadBranch: "feature/old-ref",
gitStatus: null,
});
assert.equal(update, null);
});
it("returns null when the stored thread branch already matches git status", () => {
it("returns null when the stored thread ref already matches git status", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "effect-atom",
gitStatus: status({ branch: "effect-atom" }),
gitStatus: status({ refName: "effect-atom" }),
});
assert.equal(update, null);
});
it("returns null when git status is detached HEAD but the thread already has a branch", () => {
it("returns null when git status is detached HEAD but the thread already has a ref", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "effect-atom",
gitStatus: status({ branch: null }),
gitStatus: status({ refName: null }),
});
assert.equal(update, null);
});
it("does not regress a semantic thread branch back to a temporary worktree branch", () => {
it("does not regress a semantic thread ref back to a temporary worktree ref", () => {
const update = resolveLiveThreadBranchUpdate({
threadBranch: "t3code/github-query-rate-limit",
gitStatus: status({ branch: "t3code/bda76797" }),
gitStatus: status({ refName: "t3code/bda76797" }),
});
assert.equal(update, null);
@@ -1032,31 +1033,31 @@ describe("resolveLiveThreadBranchUpdate", () => {
});
describe("resolveAutoFeatureBranchName", () => {
it("uses semantic preferred branch names when available", () => {
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
assert.equal(branch, "feature/fix-toast-copy");
it("uses semantic preferred ref names when available", () => {
const ref = resolveAutoFeatureBranchName(["main", "feature/other"], "fix toast copy");
assert.equal(ref, "feature/fix-toast-copy");
});
it("normalizes preferred names that already include a branch namespace", () => {
const branch = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
assert.equal(branch, "feature/refine-toolbar-actions");
it("normalizes preferred names that already include a ref namespace", () => {
const ref = resolveAutoFeatureBranchName(["main"], "feature/refine-toolbar-actions");
assert.equal(ref, "feature/refine-toolbar-actions");
});
it("increments suffix when the preferred branch name already exists", () => {
const branch = resolveAutoFeatureBranchName(
it("increments suffix when the preferred ref name already exists", () => {
const ref = resolveAutoFeatureBranchName(
["main", "feature/fix-toast-copy", "feature/fix-toast-copy-2"],
"fix toast copy",
);
assert.equal(branch, "feature/fix-toast-copy-3");
assert.equal(ref, "feature/fix-toast-copy-3");
});
it("treats existing branch names as case-insensitive for collision checks", () => {
const branch = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
assert.equal(branch, "feature/ticket-1-2");
it("treats existing ref names as case-insensitive for collision checks", () => {
const ref = resolveAutoFeatureBranchName(["Feature/Ticket-1"], "feature/ticket-1");
assert.equal(ref, "feature/ticket-1-2");
});
it("falls back to feature/update when no preferred name is provided", () => {
const branch = resolveAutoFeatureBranchName(["main"]);
assert.equal(branch, "feature/update");
const ref = resolveAutoFeatureBranchName(["main"]);
assert.equal(ref, "feature/update");
});
});
@@ -1,7 +1,7 @@
import type {
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
VcsStatusResult,
} from "@t3tools/contracts";
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
@@ -46,7 +46,7 @@ export function buildGitActionProgressStages(input: {
featureBranch?: boolean;
shouldPushBeforePr?: boolean;
}): string[] {
const branchStages = input.featureBranch ? ["Preparing feature branch..."] : [];
const branchStages = input.featureBranch ? ["Preparing feature ref..."] : [];
const pushStage = input.pushTarget ? `Pushing to ${input.pushTarget}...` : "Pushing...";
const prStages = [
"Preparing PR...",
@@ -77,17 +77,17 @@ export function buildGitActionProgressStages(input: {
}
export function buildMenuItems(
gitStatus: GitStatusResult | null,
gitStatus: VcsStatusResult | null,
isBusy: boolean,
hasOriginRemote = true,
hasPrimaryRemote = true,
): GitActionMenuItem[] {
if (!gitStatus) return [];
const hasBranch = gitStatus.branch !== null;
const hasBranch = gitStatus.refName !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.pr?.state === "open";
const isBehind = gitStatus.behindCount > 0;
const canPushWithoutUpstream = hasOriginRemote && !gitStatus.hasUpstream;
const canPushWithoutUpstream = hasPrimaryRemote && !gitStatus.hasUpstream;
const canCommit = !isBusy && hasChanges;
const canPush =
!isBusy &&
@@ -143,10 +143,10 @@ export function buildMenuItems(
}
export function resolveQuickAction(
gitStatus: GitStatusResult | null,
gitStatus: VcsStatusResult | null,
isBusy: boolean,
isDefaultBranch = false,
hasOriginRemote = true,
isDefaultRef = false,
hasPrimaryRemote = true,
): GitQuickAction {
if (isBusy) {
return { label: "Commit", disabled: true, kind: "show_hint", hint: "Git action in progress." };
@@ -161,7 +161,7 @@ export function resolveQuickAction(
};
}
const hasBranch = gitStatus.branch !== null;
const hasBranch = gitStatus.refName !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.pr?.state === "open";
const isAhead = gitStatus.aheadCount > 0;
@@ -173,15 +173,15 @@ export function resolveQuickAction(
label: "Commit",
disabled: true,
kind: "show_hint",
hint: "Create and checkout a branch before pushing or opening a PR.",
hint: "Create and checkout a ref before pushing or opening a PR.",
};
}
if (hasChanges) {
if (!gitStatus.hasUpstream && !hasOriginRemote) {
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
return { label: "Commit", disabled: false, kind: "run_action", action: "commit" };
}
if (hasOpenPr || isDefaultBranch) {
if (hasOpenPr || isDefaultRef) {
return { label: "Commit & push", disabled: false, kind: "run_action", action: "commit_push" };
}
return {
@@ -193,7 +193,7 @@ export function resolveQuickAction(
}
if (!gitStatus.hasUpstream) {
if (!hasOriginRemote) {
if (!hasPrimaryRemote) {
if (hasOpenPr && !isAhead) {
return { label: "View PR", disabled: false, kind: "open_pr" };
}
@@ -215,12 +215,12 @@ export function resolveQuickAction(
hint: "No local commits to push.",
};
}
if (hasOpenPr || isDefaultBranch) {
if (hasOpenPr || isDefaultRef) {
return {
label: "Push",
disabled: false,
kind: "run_action",
action: isDefaultBranch ? "commit_push" : "push",
action: isDefaultRef ? "commit_push" : "push",
};
}
return {
@@ -233,7 +233,7 @@ export function resolveQuickAction(
if (isDiverged) {
return {
label: "Sync branch",
label: "Sync ref",
disabled: true,
kind: "show_hint",
hint: "Branch has diverged from upstream. Rebase/merge first.",
@@ -249,12 +249,12 @@ export function resolveQuickAction(
}
if (isAhead) {
if (hasOpenPr || isDefaultBranch) {
if (hasOpenPr || isDefaultRef) {
return {
label: "Push",
disabled: false,
kind: "run_action",
action: isDefaultBranch ? "commit_push" : "push",
action: isDefaultRef ? "commit_push" : "push",
};
}
return {
@@ -279,9 +279,9 @@ export function resolveQuickAction(
export function requiresDefaultBranchConfirmation(
action: GitStackedAction,
isDefaultBranch: boolean,
isDefaultRef: boolean,
): boolean {
if (!isDefaultBranch) return false;
if (!isDefaultRef) return false;
return (
action === "push" ||
action === "create_pr" ||
@@ -296,18 +296,18 @@ export function resolveDefaultBranchActionDialogCopy(input: {
includesCommit: boolean;
}): DefaultBranchActionDialogCopy {
const branchLabel = input.branchName;
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
const suffix = ` on "${branchLabel}". You can continue on this ref or create a feature ref and run the same action there.`;
if (input.action === "push" || input.action === "commit_push") {
if (input.includesCommit) {
return {
title: "Commit & push to default branch?",
title: "Commit & push to default ref?",
description: `This action will commit and push changes${suffix}`,
continueLabel: `Commit & push to ${branchLabel}`,
};
}
return {
title: "Push to default branch?",
title: "Push to default ref?",
description: `This action will push local commits${suffix}`,
continueLabel: `Push to ${branchLabel}`,
};
@@ -315,13 +315,13 @@ export function resolveDefaultBranchActionDialogCopy(input: {
if (input.includesCommit) {
return {
title: "Commit, push & create PR from default branch?",
title: "Commit, push & create PR from default ref?",
description: `This action will commit, push, and create a PR${suffix}`,
continueLabel: `Commit, push & create PR`,
};
}
return {
title: "Push & create PR from default branch?",
title: "Push & create PR from default ref?",
description: `This action will push local commits and create a PR${suffix}`,
continueLabel: "Push & create PR",
};
@@ -341,31 +341,31 @@ export function resolveThreadBranchUpdate(
export function resolveLiveThreadBranchUpdate(input: {
threadBranch: string | null;
gitStatus: GitStatusResult | null;
gitStatus: VcsStatusResult | null;
}): { branch: string | null } | null {
if (!input.gitStatus) {
return null;
}
if (input.gitStatus.branch === null && input.threadBranch !== null) {
if (input.gitStatus.refName === null && input.threadBranch !== null) {
return null;
}
if (input.threadBranch === input.gitStatus.branch) {
if (input.threadBranch === input.gitStatus.refName) {
return null;
}
if (
input.threadBranch !== null &&
input.gitStatus.branch !== null &&
input.gitStatus.refName !== null &&
!isTemporaryWorktreeBranch(input.threadBranch) &&
isTemporaryWorktreeBranch(input.gitStatus.branch)
isTemporaryWorktreeBranch(input.gitStatus.refName)
) {
return null;
}
return {
branch: input.gitStatus.branch,
branch: input.gitStatus.refName,
};
}
+58 -32
View File
@@ -3,7 +3,7 @@ import type {
GitActionProgressEvent,
GitRunStackedActionResult,
GitStackedAction,
GitStatusResult,
VcsStatusResult,
} from "@t3tools/contracts";
import { useIsMutating, useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
@@ -54,6 +54,7 @@ import { readEnvironmentApi } from "~/environmentApi";
import { readLocalApi } from "~/localApi";
import { useStore } from "~/store";
import { createThreadSelectorByRef } from "~/storeSelectors";
import { resolveVcsActionPresentation, resolveVcsTerms } from "~/vcsPresentation";
interface GitActionsControlProps {
gitCwd: string | null;
@@ -89,7 +90,7 @@ interface RunGitActionWithToastInput {
commitMessage?: string;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
statusOverride?: VcsStatusResult | null;
featureBranch?: boolean;
progressToastId?: GitActionToastId;
filePaths?: string[];
@@ -121,18 +122,18 @@ function getMenuActionDisabledReason({
item,
gitStatus,
isBusy,
hasOriginRemote,
hasPrimaryRemote,
}: {
item: GitActionMenuItem;
gitStatus: GitStatusResult | null;
gitStatus: VcsStatusResult | null;
isBusy: boolean;
hasOriginRemote: boolean;
hasPrimaryRemote: boolean;
}): string | null {
if (!item.disabled) return null;
if (isBusy) return "Git action in progress.";
if (!gitStatus) return "Git status is unavailable.";
const hasBranch = gitStatus.branch !== null;
const hasBranch = gitStatus.refName !== null;
const hasChanges = gitStatus.hasWorkingTreeChanges;
const hasOpenPr = gitStatus.pr?.state === "open";
const isAhead = gitStatus.aheadCount > 0;
@@ -147,7 +148,7 @@ function getMenuActionDisabledReason({
if (item.id === "push") {
if (!hasBranch) {
return "Detached HEAD: checkout a branch before pushing.";
return "Detached HEAD: checkout a refName before pushing.";
}
if (hasChanges) {
return "Commit or stash local changes before pushing.";
@@ -155,7 +156,7 @@ function getMenuActionDisabledReason({
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before pushing.";
}
if (!gitStatus.hasUpstream && !hasOriginRemote) {
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
return 'Add an "origin" remote before pushing.';
}
if (!isAhead) {
@@ -168,12 +169,12 @@ function getMenuActionDisabledReason({
return "View PR is currently unavailable.";
}
if (!hasBranch) {
return "Detached HEAD: checkout a branch before creating a PR.";
return "Detached HEAD: checkout a refName before creating a PR.";
}
if (hasChanges) {
return "Commit local changes before creating a PR.";
}
if (!gitStatus.hasUpstream && !hasOriginRemote) {
if (!gitStatus.hasUpstream && !hasPrimaryRemote) {
return 'Add an "origin" remote before creating a PR.';
}
if (!isAhead) {
@@ -324,8 +325,12 @@ export default function GitActionsControl({
});
// Default to true while loading so we don't flash init controls.
const isRepo = gitStatus?.isRepo ?? true;
const hasOriginRemote = gitStatus?.hasOriginRemote ?? false;
const gitStatusForActions = gitStatus;
const vcsKind = gitStatus?.kind ?? null;
const vcsTerms = resolveVcsTerms(vcsKind);
const vcsActionPresentation = resolveVcsActionPresentation(vcsKind);
const supportsGitWorkflowActions = !isRepo || vcsActionPresentation.supportsGitWorkflowActions;
const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
const gitStatusForActions = supportsGitWorkflowActions ? gitStatus : null;
const allFiles = gitStatusForActions?.workingTree.files ?? [];
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
@@ -382,18 +387,18 @@ export default function GitActionsControl({
persistThreadBranchSync,
]);
const isDefaultBranch = useMemo(() => {
return gitStatusForActions?.isDefaultBranch ?? false;
}, [gitStatusForActions?.isDefaultBranch]);
const isDefaultRef = useMemo(() => {
return gitStatusForActions?.isDefaultRef ?? false;
}, [gitStatusForActions?.isDefaultRef]);
const gitActionMenuItems = useMemo(
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasOriginRemote),
[gitStatusForActions, hasOriginRemote, isGitActionRunning],
() => buildMenuItems(gitStatusForActions, isGitActionRunning, hasPrimaryRemote),
[gitStatusForActions, hasPrimaryRemote, isGitActionRunning],
);
const quickAction = useMemo(
() =>
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultBranch, hasOriginRemote),
[gitStatusForActions, hasOriginRemote, isDefaultBranch, isGitActionRunning],
resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultRef, hasPrimaryRemote),
[gitStatusForActions, hasPrimaryRemote, isDefaultRef, isGitActionRunning],
);
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
@@ -497,8 +502,8 @@ export default function GitActionsControl({
filePaths,
}: RunGitActionWithToastInput) => {
const actionStatus = statusOverride ?? gitStatusForActions;
const actionBranch = actionStatus?.branch ?? null;
const actionIsDefaultBranch = featureBranch ? false : isDefaultBranch;
const actionBranch = actionStatus?.refName ?? null;
const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
const actionCanCommit =
action === "commit" || action === "commit_push" || action === "commit_push_pr";
const includesCommit =
@@ -775,8 +780,8 @@ export default function GitActionsControl({
title: result.status === "pulled" ? "Pulled" : "Already up to date",
description:
result.status === "pulled"
? `Updated ${result.branch} from ${result.upstreamBranch ?? "upstream"}`
: `${result.branch} is already synchronized.`,
? `Updated ${result.refName} from ${result.upstreamRef ?? "upstream"}`
: `${result.refName} is already synchronized.`,
data: threadToastData,
}),
error: (err) => ({
@@ -874,6 +879,25 @@ export default function GitActionsControl({
>
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
</Button>
) : !supportsGitWorkflowActions ? (
<Popover>
<PopoverTrigger
openOnHover
render={
<Button
aria-disabled="true"
className="cursor-not-allowed opacity-70"
size="xs"
variant="outline"
/>
}
>
{vcsTerms.systemName} {vcsTerms.repositoryNoun}
</PopoverTrigger>
<PopoverPopup tooltipStyle side="bottom" align="end">
{vcsActionPresentation.unsupportedGitWorkflowDescription}
</PopoverPopup>
</Popover>
) : (
<Group aria-label="Git actions" className="shrink-0">
{quickActionDisabledReason ? (
@@ -934,7 +958,7 @@ export default function GitActionsControl({
item,
gitStatus: gitStatusForActions,
isBusy: isGitActionRunning,
hasOriginRemote,
hasPrimaryRemote,
});
if (item.disabled && disabledReason) {
return (
@@ -969,13 +993,13 @@ export default function GitActionsControl({
</MenuItem>
);
})}
{gitStatusForActions?.branch === null && (
{gitStatusForActions?.refName === null && (
<p className="px-2 py-1.5 text-xs text-warning">
Detached HEAD: create and checkout a branch to enable push and PR actions.
Detached HEAD: create and checkout a refName to enable push and PR actions.
</p>
)}
{gitStatusForActions &&
gitStatusForActions.branch !== null &&
gitStatusForActions.refName !== null &&
!gitStatusForActions.hasWorkingTreeChanges &&
gitStatusForActions.behindCount > 0 &&
gitStatusForActions.aheadCount === 0 && (
@@ -1013,10 +1037,12 @@ export default function GitActionsControl({
<span className="text-muted-foreground">Branch</span>
<span className="flex items-center justify-between gap-2">
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
{gitStatusForActions?.refName ?? "(detached HEAD)"}
</span>
{isDefaultBranch && (
<span className="text-right text-warning text-xs">Warning: default branch</span>
{isDefaultRef && (
<span className="text-right text-warning text-xs">
Warning: default refName
</span>
)}
</span>
</div>
@@ -1149,7 +1175,7 @@ export default function GitActionsControl({
disabled={noneSelected}
onClick={runDialogActionOnNewBranch}
>
Commit on new branch
Commit on new refName
</Button>
<Button size="sm" disabled={noneSelected} onClick={runDialogAction}>
Commit
@@ -1169,7 +1195,7 @@ export default function GitActionsControl({
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
{pendingDefaultBranchActionCopy?.title ?? "Run action on default refName?"}
</DialogTitle>
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
</DialogHeader>
@@ -256,13 +256,13 @@ function resolveWsRpc(tag: string): unknown {
if (tag === WS_METHODS.serverGetConfig) {
return fixture.serverConfig;
}
if (tag === WS_METHODS.gitListBranches) {
if (tag === WS_METHODS.vcsListRefs) {
return {
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 1,
branches: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
refs: [{ name: "main", current: true, isDefault: true, worktreePath: null }],
};
}
if (tag === WS_METHODS.projectsSearchEntries) {
@@ -1,5 +1,5 @@
import { scopeProjectRef, scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime";
import type { GitStatusResult } from "@t3tools/contracts";
import type { VcsStatusResult } from "@t3tools/contracts";
import { CloudIcon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
import { useMemo } from "react";
import { usePrimaryEnvironmentId } from "../environments/primary";
@@ -28,7 +28,7 @@ export interface TerminalStatusIndicator {
pulse: boolean;
}
export type ThreadPr = GitStatusResult["pr"];
export type ThreadPr = VcsStatusResult["pr"];
export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
if (!pr) return null;
@@ -62,9 +62,9 @@ export function prStatusIndicator(pr: ThreadPr): PrStatusIndicator | null {
export function resolveThreadPr(
threadBranch: string | null,
gitStatus: GitStatusResult | null,
gitStatus: VcsStatusResult | null,
): ThreadPr | null {
if (threadBranch === null || gitStatus === null || gitStatus.branch !== threadBranch) {
if (threadBranch === null || gitStatus === null || gitStatus.refName !== threadBranch) {
return null;
}
+12 -7
View File
@@ -17,6 +17,8 @@ import { Toggle } from "../ui/toggle";
import { SidebarTrigger } from "../ui/sidebar";
import { OpenInPicker } from "./OpenInPicker";
import { usePrimaryEnvironmentId } from "../../environments/primary";
import { resolveVcsTerms } from "../../vcsPresentation";
import type { VcsDriverKind } from "@t3tools/contracts";
interface ChatHeaderProps {
activeThreadEnvironmentId: EnvironmentId;
@@ -24,7 +26,8 @@ interface ChatHeaderProps {
draftId?: DraftId;
activeThreadTitle: string;
activeProjectName: string | undefined;
isGitRepo: boolean;
isVcsRepo: boolean;
vcsKind: VcsDriverKind | null;
openInCwd: string | null;
activeProjectScripts: ProjectScript[] | undefined;
preferredScriptId: string | null;
@@ -50,7 +53,8 @@ export const ChatHeader = memo(function ChatHeader({
draftId,
activeThreadTitle,
activeProjectName,
isGitRepo,
isVcsRepo,
vcsKind,
openInCwd,
activeProjectScripts,
preferredScriptId,
@@ -72,6 +76,7 @@ export const ChatHeader = memo(function ChatHeader({
const primaryEnvironmentId = usePrimaryEnvironmentId();
const isRemoteEnvironment =
primaryEnvironmentId !== null && activeThreadEnvironmentId !== primaryEnvironmentId;
const vcsTerms = resolveVcsTerms(vcsKind);
return (
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
@@ -88,9 +93,9 @@ export const ChatHeader = memo(function ChatHeader({
<span className="min-w-0 truncate">{activeProjectName}</span>
</Badge>
)}
{activeProjectName && !isGitRepo && (
{activeProjectName && !isVcsRepo && (
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
No Git
No repository
</Badge>
)}
</div>
@@ -154,15 +159,15 @@ export const ChatHeader = memo(function ChatHeader({
aria-label="Toggle diff panel"
variant="outline"
size="xs"
disabled={!isGitRepo && !diffOpen}
disabled={!isVcsRepo && !diffOpen}
>
<DiffIcon className="size-3" />
</Toggle>
}
/>
<TooltipPopup side="bottom">
{!isGitRepo && !diffOpen
? "Diff panel is unavailable because this project is not a git repository."
{!isVcsRepo && !diffOpen
? `Diff panel is unavailable because this project is not a supported ${vcsTerms.repositoryNoun}.`
: diffToggleShortcutLabel
? `Toggle diff panel (${diffToggleShortcutLabel})`
: "Toggle diff panel"}
+11 -9
View File
@@ -23,16 +23,18 @@ export function createEnvironmentApi(rpcClient: WsRpcClient): EnvironmentApi {
filesystem: {
browse: rpcClient.filesystem.browse,
},
vcs: {
pull: rpcClient.vcs.pull,
refreshStatus: rpcClient.vcs.refreshStatus,
onStatus: (input, callback, options) => rpcClient.vcs.onStatus(input, callback, options),
listRefs: rpcClient.vcs.listRefs,
createWorktree: rpcClient.vcs.createWorktree,
removeWorktree: rpcClient.vcs.removeWorktree,
createRef: rpcClient.vcs.createRef,
switchRef: rpcClient.vcs.switchRef,
init: rpcClient.vcs.init,
},
git: {
pull: rpcClient.git.pull,
refreshStatus: rpcClient.git.refreshStatus,
onStatus: (input, callback, options) => rpcClient.git.onStatus(input, callback, options),
listBranches: rpcClient.git.listBranches,
createWorktree: rpcClient.git.createWorktree,
removeWorktree: rpcClient.git.removeWorktree,
createBranch: rpcClient.git.createBranch,
checkout: rpcClient.git.checkout,
init: rpcClient.git.init,
resolvePullRequest: rpcClient.git.resolvePullRequest,
preparePullRequestThread: rpcClient.git.preparePullRequestThread,
},
@@ -85,16 +85,7 @@ function createTestClient() {
openInEditor: vi.fn(async () => undefined),
},
git: {
pull: vi.fn(async () => undefined),
refreshStatus: vi.fn(async () => undefined),
onStatus: vi.fn(() => () => undefined),
runStackedAction: vi.fn(async () => ({}) as any),
listBranches: vi.fn(async () => []),
createWorktree: vi.fn(async () => undefined),
removeWorktree: vi.fn(async () => undefined),
createBranch: vi.fn(async () => undefined),
checkout: vi.fn(async () => undefined),
init: vi.fn(async () => undefined),
resolvePullRequest: vi.fn(async () => undefined),
preparePullRequestThread: vi.fn(async () => undefined),
},
+1 -1
View File
@@ -209,7 +209,7 @@ export function useThreadActions() {
}
try {
await ensureEnvironmentApi(threadRef.environmentId).git.removeWorktree({
await ensureEnvironmentApi(threadRef.environmentId).vcs.removeWorktree({
cwd: threadProject.cwd,
path: orphanedWorktreePath,
force: true,
+5 -5
View File
@@ -11,7 +11,7 @@ vi.mock("../wsRpcClient", () => ({
}));
import type { InfiniteData } from "@tanstack/react-query";
import { EnvironmentId, type GitListBranchesResult } from "@t3tools/contracts";
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
import {
gitBranchSearchInfiniteQueryOptions,
@@ -22,15 +22,15 @@ import {
invalidateGitQueries,
} from "./gitReactQuery";
const BRANCH_QUERY_RESULT: GitListBranchesResult = {
branches: [],
const BRANCH_QUERY_RESULT: VcsListRefsResult = {
refs: [],
isRepo: true,
hasOriginRemote: true,
hasPrimaryRemote: true,
nextCursor: null,
totalCount: 0,
};
const BRANCH_SEARCH_RESULT: InfiniteData<GitListBranchesResult, number> = {
const BRANCH_SEARCH_RESULT: InfiniteData<VcsListRefsResult, number> = {
pages: [BRANCH_QUERY_RESULT],
pageParams: [0],
};
+38 -20
View File
@@ -19,17 +19,17 @@ const GIT_BRANCHES_PAGE_SIZE = 100;
export const gitQueryKeys = {
all: ["git"] as const,
branches: (environmentId: EnvironmentId | null, cwd: string | null) =>
["git", "branches", environmentId ?? null, cwd] as const,
refs: (environmentId: EnvironmentId | null, cwd: string | null) =>
["git", "refs", environmentId ?? null, cwd] as const,
branchSearch: (environmentId: EnvironmentId | null, cwd: string | null, query: string) =>
["git", "branches", environmentId ?? null, cwd, "search", query] as const,
["git", "refs", environmentId ?? null, cwd, "search", query] as const,
};
export const gitMutationKeys = {
init: (environmentId: EnvironmentId | null, cwd: string | null) =>
["git", "mutation", "init", environmentId ?? null, cwd] as const,
checkout: (environmentId: EnvironmentId | null, cwd: string | null) =>
["git", "mutation", "checkout", environmentId ?? null, cwd] as const,
switchRef: (environmentId: EnvironmentId | null, cwd: string | null) =>
["git", "mutation", "switchRef", environmentId ?? null, cwd] as const,
runStackedAction: (environmentId: EnvironmentId | null, cwd: string | null) =>
["git", "mutation", "run-stacked-action", environmentId ?? null, cwd] as const,
pull: (environmentId: EnvironmentId | null, cwd: string | null) =>
@@ -45,7 +45,7 @@ export function invalidateGitQueries(
const environmentId = input?.environmentId ?? null;
const cwd = input?.cwd ?? null;
if (cwd !== null) {
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, cwd) });
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) });
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.all });
@@ -60,9 +60,12 @@ function invalidateGitBranchQueries(
return Promise.resolve();
}
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.branches(environmentId, cwd) });
return queryClient.invalidateQueries({ queryKey: gitQueryKeys.refs(environmentId, cwd) });
}
/**
* @deprecated Use a VCS-named query helper once the UI naming migration lands.
*/
export function gitBranchSearchInfiniteQueryOptions(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
@@ -75,10 +78,10 @@ export function gitBranchSearchInfiniteQueryOptions(input: {
queryKey: gitQueryKeys.branchSearch(input.environmentId, input.cwd, normalizedQuery),
initialPageParam: 0,
queryFn: async ({ pageParam }) => {
if (!input.cwd) throw new Error("Git branches are unavailable.");
if (!input.environmentId) throw new Error("Git branches are unavailable.");
if (!input.cwd) throw new Error("Git refs are unavailable.");
if (!input.environmentId) throw new Error("Git refs are unavailable.");
const api = ensureEnvironmentApi(input.environmentId);
return api.git.listBranches({
return api.vcs.listRefs({
cwd: input.cwd,
...(normalizedQuery.length > 0 ? { query: normalizedQuery } : {}),
cursor: pageParam,
@@ -121,6 +124,9 @@ export function gitResolvePullRequestQueryOptions(input: {
});
}
/**
* @deprecated Use a VCS-named mutation helper once the UI naming migration lands.
*/
export function gitInitMutationOptions(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
@@ -131,7 +137,7 @@ export function gitInitMutationOptions(input: {
mutationFn: async () => {
if (!input.cwd || !input.environmentId) throw new Error("Git init is unavailable.");
const api = ensureEnvironmentApi(input.environmentId);
return api.git.init({ cwd: input.cwd });
return api.vcs.init({ cwd: input.cwd });
},
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
@@ -139,17 +145,20 @@ export function gitInitMutationOptions(input: {
});
}
/**
* @deprecated Use a VCS-named mutation helper once the UI naming migration lands.
*/
export function gitCheckoutMutationOptions(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
queryClient: QueryClient;
}) {
return mutationOptions({
mutationKey: gitMutationKeys.checkout(input.environmentId, input.cwd),
mutationFn: async (branch: string) => {
if (!input.cwd || !input.environmentId) throw new Error("Git checkout is unavailable.");
mutationKey: gitMutationKeys.switchRef(input.environmentId, input.cwd),
mutationFn: async (refName: string) => {
if (!input.cwd || !input.environmentId) throw new Error("Git switchRef is unavailable.");
const api = ensureEnvironmentApi(input.environmentId);
return api.git.checkout({ cwd: input.cwd, branch });
return api.vcs.switchRef({ cwd: input.cwd, refName });
},
onSettled: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
@@ -198,6 +207,9 @@ export function gitRunStackedActionMutationOptions(input: {
});
}
/**
* @deprecated Use a VCS-named mutation helper once the UI naming migration lands.
*/
export function gitPullMutationOptions(input: {
environmentId: EnvironmentId | null;
cwd: string | null;
@@ -208,7 +220,7 @@ export function gitPullMutationOptions(input: {
mutationFn: async () => {
if (!input.cwd || !input.environmentId) throw new Error("Git pull is unavailable.");
const api = ensureEnvironmentApi(input.environmentId);
return api.git.pull({ cwd: input.cwd });
return api.vcs.pull({ cwd: input.cwd });
},
onSuccess: async () => {
await invalidateGitBranchQueries(input.queryClient, input.environmentId, input.cwd);
@@ -216,6 +228,9 @@ export function gitPullMutationOptions(input: {
});
}
/**
* @deprecated Use a VCS-named mutation helper once the UI naming migration lands.
*/
export function gitCreateWorktreeMutationOptions(input: {
environmentId: EnvironmentId | null;
queryClient: QueryClient;
@@ -223,12 +238,12 @@ export function gitCreateWorktreeMutationOptions(input: {
return mutationOptions({
mutationKey: ["git", "mutation", "create-worktree", input.environmentId ?? null] as const,
mutationFn: (
args: Parameters<ReturnType<typeof ensureEnvironmentApi>["git"]["createWorktree"]>[0],
args: Parameters<ReturnType<typeof ensureEnvironmentApi>["vcs"]["createWorktree"]>[0],
) => {
if (!input.environmentId) {
throw new Error("Worktree creation is unavailable.");
}
return ensureEnvironmentApi(input.environmentId).git.createWorktree(args);
return ensureEnvironmentApi(input.environmentId).vcs.createWorktree(args);
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient, { environmentId: input.environmentId });
@@ -236,6 +251,9 @@ export function gitCreateWorktreeMutationOptions(input: {
});
}
/**
* @deprecated Use a VCS-named mutation helper once the UI naming migration lands.
*/
export function gitRemoveWorktreeMutationOptions(input: {
environmentId: EnvironmentId | null;
queryClient: QueryClient;
@@ -243,12 +261,12 @@ export function gitRemoveWorktreeMutationOptions(input: {
return mutationOptions({
mutationKey: ["git", "mutation", "remove-worktree", input.environmentId ?? null] as const,
mutationFn: (
args: Parameters<ReturnType<typeof ensureEnvironmentApi>["git"]["removeWorktree"]>[0],
args: Parameters<ReturnType<typeof ensureEnvironmentApi>["vcs"]["removeWorktree"]>[0],
) => {
if (!input.environmentId) {
throw new Error("Worktree removal is unavailable.");
}
return ensureEnvironmentApi(input.environmentId).git.removeWorktree(args);
return ensureEnvironmentApi(input.environmentId).vcs.removeWorktree(args);
},
onSuccess: async () => {
await invalidateGitQueries(input.queryClient, { environmentId: input.environmentId });
+32 -29
View File
@@ -1,4 +1,4 @@
import { EnvironmentId, type GitStatusResult } from "@t3tools/contracts";
import { EnvironmentId, type VcsStatusResult } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { WsRpcClient } from "../rpc/wsRpcClient";
@@ -33,17 +33,18 @@ function registerListener<T>(listeners: Set<(event: T) => void>, listener: (even
};
}
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const gitStatusListeners = new Set<(event: VcsStatusResult) => void>();
const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const OTHER_ENVIRONMENT_ID = EnvironmentId.make("environment-remote");
const TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/repo" } as const;
const FRESH_TARGET = { environmentId: ENVIRONMENT_ID, cwd: "/fresh" } as const;
const BASE_STATUS: GitStatusResult = {
const BASE_STATUS: VcsStatusResult = {
kind: "git",
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/push-status",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/push-status",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
@@ -55,21 +56,21 @@ const BASE_STATUS: GitStatusResult = {
const gitClient = {
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
refName: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
onStatus: vi.fn((input: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
};
function emitGitStatus(event: GitStatusResult) {
function emitGitStatus(event: VcsStatusResult) {
for (const listener of gitStatusListeners) {
listener(event);
}
}
function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
const listeners = new Set<(event: GitStatusResult) => void>();
const listeners = new Set<(event: VcsStatusResult) => void>();
const client = {
dispose: vi.fn(async () => undefined),
reconnect: vi.fn(async () => undefined),
@@ -89,22 +90,24 @@ function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
shell: {
openInEditor: vi.fn(async () => undefined),
},
git: {
vcs: {
pull: vi.fn(async () => undefined),
refreshStatus: vi.fn(async (input: { cwd: string }) => ({
...BASE_STATUS,
branch: `${input.cwd}-refreshed`,
refName: `${input.cwd}-refreshed`,
})),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
onStatus: vi.fn((_: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
registerListener(listeners, listener),
),
runStackedAction: vi.fn(async () => ({}) as any),
listBranches: vi.fn(async () => []),
listRefs: vi.fn(async () => []),
createWorktree: vi.fn(async () => undefined),
removeWorktree: vi.fn(async () => undefined),
createBranch: vi.fn(async () => undefined),
checkout: vi.fn(async () => undefined),
createRef: vi.fn(async () => undefined),
switchRef: vi.fn(async () => undefined),
init: vi.fn(async () => undefined),
},
git: {
runStackedAction: vi.fn(async () => ({}) as any),
resolvePullRequest: vi.fn(async () => undefined),
preparePullRequestThread: vi.fn(async () => undefined),
},
@@ -155,7 +158,7 @@ function createRegisteredGitStatusClient(environmentId: EnvironmentId) {
return {
client,
emit: (event: GitStatusResult) => {
emit: (event: VcsStatusResult) => {
for (const listener of listeners) {
listener(event);
}
@@ -219,7 +222,7 @@ describe("gitStatusState", () => {
expect(gitClient.onStatus).toHaveBeenCalledOnce();
expect(gitClient.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
expect(refreshed).toEqual({ ...BASE_STATUS, branch: "/repo-refreshed" });
expect(refreshed).toEqual({ ...BASE_STATUS, refName: "/repo-refreshed" });
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: BASE_STATUS,
error: null,
@@ -231,17 +234,17 @@ describe("gitStatusState", () => {
});
it("keeps git status subscriptions isolated by environment when cwds match", () => {
const localListeners = new Set<(event: GitStatusResult) => void>();
const remoteListeners = new Set<(event: GitStatusResult) => void>();
const localListeners = new Set<(event: VcsStatusResult) => void>();
const remoteListeners = new Set<(event: VcsStatusResult) => void>();
const localClient = {
refreshStatus: vi.fn(),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
onStatus: vi.fn((_: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
registerListener(localListeners, listener),
),
};
const remoteClient = {
refreshStatus: vi.fn(),
onStatus: vi.fn((_: { cwd: string }, listener: (event: GitStatusResult) => void) =>
onStatus: vi.fn((_: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
registerListener(remoteListeners, listener),
),
};
@@ -254,11 +257,11 @@ describe("gitStatusState", () => {
listener(BASE_STATUS);
}
for (const listener of remoteListeners) {
listener({ ...BASE_STATUS, branch: "remote-branch" });
listener({ ...BASE_STATUS, refName: "remote-refName" });
}
expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
expect(getGitStatusSnapshot(remoteTarget).data?.branch).toBe("remote-branch");
expect(getGitStatusSnapshot(TARGET).data?.refName).toBe("feature/push-status");
expect(getGitStatusSnapshot(remoteTarget).data?.refName).toBe("remote-refName");
releaseLocal();
releaseRemote();
@@ -292,7 +295,7 @@ describe("gitStatusState", () => {
const release = watchGitStatus(TARGET);
firstClient.emit(BASE_STATUS);
expect(getGitStatusSnapshot(TARGET).data?.branch).toBe("feature/push-status");
expect(getGitStatusSnapshot(TARGET).data?.refName).toBe("feature/push-status");
serviceHarness.connections.delete(ENVIRONMENT_ID);
for (const listener of serviceHarness.listeners) {
@@ -307,10 +310,10 @@ describe("gitStatusState", () => {
});
const secondClient = createRegisteredGitStatusClient(ENVIRONMENT_ID);
secondClient.emit({ ...BASE_STATUS, branch: "reconnected-branch" });
secondClient.emit({ ...BASE_STATUS, refName: "reconnected-refName" });
expect(getGitStatusSnapshot(TARGET)).toEqual({
data: { ...BASE_STATUS, branch: "reconnected-branch" },
data: { ...BASE_STATUS, refName: "reconnected-refName" },
error: null,
cause: null,
isPending: false,
+7 -7
View File
@@ -2,7 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
import {
type EnvironmentId,
type GitManagerServiceError,
type GitStatusResult,
type VcsStatusResult,
} from "@t3tools/contracts";
import { Cause } from "effect";
import { Atom } from "effect/unstable/reactivity";
@@ -16,13 +16,13 @@ import {
import type { WsRpcClient } from "~/rpc/wsRpcClient";
interface GitStatusState {
readonly data: GitStatusResult | null;
readonly data: VcsStatusResult | null;
readonly error: GitManagerServiceError | null;
readonly cause: Cause.Cause<GitManagerServiceError> | null;
readonly isPending: boolean;
}
type GitStatusClient = Pick<WsRpcClient["git"], "onStatus" | "refreshStatus">;
type GitStatusClient = Pick<WsRpcClient["vcs"], "onStatus" | "refreshStatus">;
interface ResolvedGitStatusClient {
readonly clientIdentity: string;
readonly client: GitStatusClient;
@@ -56,7 +56,7 @@ const EMPTY_GIT_STATUS_ATOM = Atom.make(EMPTY_GIT_STATUS_STATE).pipe(
const NOOP: () => void = () => undefined;
const watchedGitStatuses = new Map<string, WatchedGitStatus>();
const knownGitStatusKeys = new Set<string>();
const gitStatusRefreshInFlight = new Map<string, Promise<GitStatusResult>>();
const gitStatusRefreshInFlight = new Map<string, Promise<VcsStatusResult>>();
const gitStatusLastRefreshAtByKey = new Map<string, number>();
const GIT_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
@@ -83,7 +83,7 @@ function readResolvedGitStatusClient(target: GitStatusTarget): ResolvedGitStatus
}
const connection = readEnvironmentConnection(target.environmentId);
return connection
? { clientIdentity: connection.environmentId, client: connection.client.git }
? { clientIdentity: connection.environmentId, client: connection.client.vcs }
: null;
}
@@ -119,7 +119,7 @@ export function watchGitStatus(target: GitStatusTarget, client?: GitStatusClient
export function refreshGitStatus(
target: GitStatusTarget,
client?: GitStatusClient,
): Promise<GitStatusResult | null> {
): Promise<VcsStatusResult | null> {
const targetKey = getGitStatusTargetKey(target);
if (targetKey === null || target.cwd === null) {
return Promise.resolve(null);
@@ -245,7 +245,7 @@ function subscribeToGitStatus(targetKey: string, cwd: string, client: GitStatusC
markGitStatusPending(targetKey);
return client.onStatus(
{ cwd },
(status: GitStatusResult) => {
(status: VcsStatusResult) => {
appAtomRegistry.set(gitStatusStateAtom(targetKey), {
data: status,
error: null,
+1 -1
View File
@@ -64,7 +64,7 @@ function normalizeCheckpointErrorMessage(error: unknown): string {
const lower = message.toLowerCase();
if (lower.includes("not a git repository")) {
return "Turn diffs are unavailable because this project is not a git repository.";
return "Turn diffs are unavailable because this project is not a repository.";
}
if (
+20 -17
View File
@@ -3,7 +3,7 @@ import {
DEFAULT_SERVER_SETTINGS,
type DesktopBridge,
EnvironmentId,
type GitStatusResult,
type VcsStatusResult,
ProjectId,
type OrchestrationShellStreamItem,
ProviderDriverKind,
@@ -34,7 +34,7 @@ function registerListener<T>(listeners: Set<(event: T) => void>, listener: (even
const terminalEventListeners = new Set<(event: TerminalEvent) => void>();
const shellStreamListeners = new Set<(event: OrchestrationShellStreamItem) => void>();
const gitStatusListeners = new Set<(event: GitStatusResult) => void>();
const gitStatusListeners = new Set<(event: VcsStatusResult) => void>();
const rpcClientMock = {
dispose: vi.fn(),
@@ -59,19 +59,21 @@ const rpcClientMock = {
shell: {
openInEditor: vi.fn(),
},
git: {
vcs: {
pull: vi.fn(),
refreshStatus: vi.fn(),
onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) =>
onStatus: vi.fn((input: { cwd: string }, listener: (event: VcsStatusResult) => void) =>
registerListener(gitStatusListeners, listener),
),
runStackedAction: vi.fn(),
listBranches: vi.fn(),
listRefs: vi.fn(),
createWorktree: vi.fn(),
removeWorktree: vi.fn(),
createBranch: vi.fn(),
checkout: vi.fn(),
createRef: vi.fn(),
switchRef: vi.fn(),
init: vi.fn(),
},
git: {
runStackedAction: vi.fn(),
resolvePullRequest: vi.fn(),
preparePullRequestThread: vi.fn(),
},
@@ -259,11 +261,12 @@ const baseServerConfig: ServerConfig = {
settings: DEFAULT_SERVER_SETTINGS,
};
const baseGitStatus: GitStatusResult = {
const baseGitStatus: VcsStatusResult = {
kind: "git",
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/streamed",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/streamed",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
@@ -351,24 +354,24 @@ describe("wsApi", () => {
const api = createEnvironmentApi(rpcClientMock as never);
const onStatus = vi.fn();
api.git.onStatus({ cwd: "/repo" }, onStatus);
api.vcs.onStatus({ cwd: "/repo" }, onStatus);
const gitStatus = baseGitStatus;
emitEvent(gitStatusListeners, gitStatus);
expect(rpcClientMock.git.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
expect(rpcClientMock.vcs.onStatus).toHaveBeenCalledWith({ cwd: "/repo" }, onStatus, undefined);
expect(onStatus).toHaveBeenCalledWith(gitStatus);
});
it("forwards git status refreshes directly to the RPC client", async () => {
rpcClientMock.git.refreshStatus.mockResolvedValue(baseGitStatus);
rpcClientMock.vcs.refreshStatus.mockResolvedValue(baseGitStatus);
const { createEnvironmentApi } = await import("./environmentApi");
const api = createEnvironmentApi(rpcClientMock as never);
await api.git.refreshStatus({ cwd: "/repo" });
await api.vcs.refreshStatus({ cwd: "/repo" });
expect(rpcClientMock.git.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
expect(rpcClientMock.vcs.refreshStatus).toHaveBeenCalledWith({ cwd: "/repo" });
});
it("forwards shell stream subscription options to the RPC client", async () => {
+12 -11
View File
@@ -1,7 +1,7 @@
import type {
GitStatusLocalResult,
GitStatusRemoteResult,
GitStatusStreamEvent,
VcsStatusLocalResult,
VcsStatusRemoteResult,
VcsStatusStreamEvent,
} from "@t3tools/contracts";
import { describe, expect, it, vi } from "vitest";
@@ -18,16 +18,17 @@ vi.mock("./wsTransport", () => ({
import { createWsRpcClient } from "./wsRpcClient";
import { type WsTransport } from "./wsTransport";
const baseLocalStatus: GitStatusLocalResult = {
const baseLocalStatus: VcsStatusLocalResult = {
kind: "git",
isRepo: true,
hasOriginRemote: true,
isDefaultBranch: false,
branch: "feature/demo",
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/demo",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
};
const baseRemoteStatus: GitStatusRemoteResult = {
const baseRemoteStatus: VcsStatusRemoteResult = {
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
@@ -35,7 +36,7 @@ const baseRemoteStatus: GitStatusRemoteResult = {
};
describe("wsRpcClient", () => {
it("reduces git status stream events into flat status snapshots", () => {
it("reduces vcs status stream events into flat status snapshots", () => {
const subscribe = vi.fn(<TValue>(_connect: unknown, listener: (value: TValue) => void) => {
for (const event of [
{
@@ -54,7 +55,7 @@ describe("wsRpcClient", () => {
hasWorkingTreeChanges: true,
},
},
] satisfies GitStatusStreamEvent[]) {
] satisfies VcsStatusStreamEvent[]) {
listener(event as TValue);
}
return () => undefined;
@@ -74,7 +75,7 @@ describe("wsRpcClient", () => {
const client = createWsRpcClient(transport as unknown as WsTransport);
const listener = vi.fn();
client.git.onStatus({ cwd: "/repo" }, listener);
client.vcs.onStatus({ cwd: "/repo" }, listener);
expect(listener.mock.calls).toEqual([
[
+34 -29
View File
@@ -2,8 +2,8 @@ import {
type GitActionProgressEvent,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type GitStatusResult,
type GitStatusStreamEvent,
type VcsStatusResult,
type VcsStatusStreamEvent,
type LocalApi,
ORCHESTRATION_WS_METHODS,
type ServerSettingsPatch,
@@ -77,24 +77,29 @@ export interface WsRpcClient {
readonly editor: Parameters<LocalApi["shell"]["openInEditor"]>[1];
}) => ReturnType<LocalApi["shell"]["openInEditor"]>;
};
readonly git: {
readonly pull: RpcUnaryMethod<typeof WS_METHODS.gitPull>;
readonly refreshStatus: RpcUnaryMethod<typeof WS_METHODS.gitRefreshStatus>;
readonly vcs: {
readonly pull: RpcUnaryMethod<typeof WS_METHODS.vcsPull>;
readonly refreshStatus: RpcUnaryMethod<typeof WS_METHODS.vcsRefreshStatus>;
readonly onStatus: (
input: RpcInput<typeof WS_METHODS.subscribeGitStatus>,
listener: (status: GitStatusResult) => void,
input: RpcInput<typeof WS_METHODS.subscribeVcsStatus>,
listener: (status: VcsStatusResult) => void,
options?: StreamSubscriptionOptions,
) => () => void;
readonly listRefs: RpcUnaryMethod<typeof WS_METHODS.vcsListRefs>;
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.vcsCreateWorktree>;
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.vcsRemoveWorktree>;
readonly createRef: RpcUnaryMethod<typeof WS_METHODS.vcsCreateRef>;
readonly switchRef: RpcUnaryMethod<typeof WS_METHODS.vcsSwitchRef>;
readonly init: RpcUnaryMethod<typeof WS_METHODS.vcsInit>;
};
/**
* Git-specific workflows. Local repository mechanics live under `vcs`.
*/
readonly git: {
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Promise<GitRunStackedActionResult>;
readonly listBranches: RpcUnaryMethod<typeof WS_METHODS.gitListBranches>;
readonly createWorktree: RpcUnaryMethod<typeof WS_METHODS.gitCreateWorktree>;
readonly removeWorktree: RpcUnaryMethod<typeof WS_METHODS.gitRemoveWorktree>;
readonly createBranch: RpcUnaryMethod<typeof WS_METHODS.gitCreateBranch>;
readonly checkout: RpcUnaryMethod<typeof WS_METHODS.gitCheckout>;
readonly init: RpcUnaryMethod<typeof WS_METHODS.gitInit>;
readonly resolvePullRequest: RpcUnaryMethod<typeof WS_METHODS.gitResolvePullRequest>;
readonly preparePullRequestThread: RpcUnaryMethod<
typeof WS_METHODS.gitPreparePullRequestThread
@@ -161,21 +166,31 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
openInEditor: (input) =>
transport.request((client) => client[WS_METHODS.shellOpenInEditor](input)),
},
git: {
pull: (input) => transport.request((client) => client[WS_METHODS.gitPull](input)),
vcs: {
pull: (input) => transport.request((client) => client[WS_METHODS.vcsPull](input)),
refreshStatus: (input) =>
transport.request((client) => client[WS_METHODS.gitRefreshStatus](input)),
transport.request((client) => client[WS_METHODS.vcsRefreshStatus](input)),
onStatus: (input, listener, options) => {
let current: GitStatusResult | null = null;
let current: VcsStatusResult | null = null;
return transport.subscribe(
(client) => client[WS_METHODS.subscribeGitStatus](input),
(event: GitStatusStreamEvent) => {
(client) => client[WS_METHODS.subscribeVcsStatus](input),
(event: VcsStatusStreamEvent) => {
current = applyGitStatusStreamEvent(current, event);
listener(current);
},
options,
);
},
listRefs: (input) => transport.request((client) => client[WS_METHODS.vcsListRefs](input)),
createWorktree: (input) =>
transport.request((client) => client[WS_METHODS.vcsCreateWorktree](input)),
removeWorktree: (input) =>
transport.request((client) => client[WS_METHODS.vcsRemoveWorktree](input)),
createRef: (input) => transport.request((client) => client[WS_METHODS.vcsCreateRef](input)),
switchRef: (input) => transport.request((client) => client[WS_METHODS.vcsSwitchRef](input)),
init: (input) => transport.request((client) => client[WS_METHODS.vcsInit](input)),
},
git: {
runStackedAction: async (input, options) => {
let result: GitRunStackedActionResult | null = null;
@@ -195,16 +210,6 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient {
throw new Error("Git action stream completed without a final result.");
},
listBranches: (input) =>
transport.request((client) => client[WS_METHODS.gitListBranches](input)),
createWorktree: (input) =>
transport.request((client) => client[WS_METHODS.gitCreateWorktree](input)),
removeWorktree: (input) =>
transport.request((client) => client[WS_METHODS.gitRemoveWorktree](input)),
createBranch: (input) =>
transport.request((client) => client[WS_METHODS.gitCreateBranch](input)),
checkout: (input) => transport.request((client) => client[WS_METHODS.gitCheckout](input)),
init: (input) => transport.request((client) => client[WS_METHODS.gitInit](input)),
resolvePullRequest: (input) =>
transport.request((client) => client[WS_METHODS.gitResolvePullRequest](input)),
preparePullRequestThread: (input) =>
+83
View File
@@ -0,0 +1,83 @@
import type { SourceControlProviderInfo } from "@t3tools/contracts";
export interface ChangeRequestPresentation {
readonly icon: "github" | "gitlab" | "azure-devops" | "change-request";
readonly providerName: string;
readonly shortName: string;
readonly longName: string;
readonly pluralLongName: string;
readonly providerLongName: string;
readonly checkoutCommandExample: string;
readonly urlExample: string;
}
const GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "github",
providerName: "GitHub",
shortName: "PR",
longName: "pull request",
pluralLongName: "pull requests",
providerLongName: "GitHub pull request",
checkoutCommandExample: "gh pr checkout 123",
urlExample: "https://github.com/owner/repo/pull/42",
};
const GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "gitlab",
providerName: "GitLab",
shortName: "MR",
longName: "merge request",
pluralLongName: "merge requests",
providerLongName: "GitLab merge request",
checkoutCommandExample: "glab mr checkout 123",
urlExample: "https://gitlab.com/group/project/-/merge_requests/42",
};
const AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "azure-devops",
providerName: "Azure DevOps",
shortName: "PR",
longName: "pull request",
pluralLongName: "pull requests",
providerLongName: "Azure DevOps pull request",
checkoutCommandExample: "az repos pr checkout --id 123",
urlExample: "https://dev.azure.com/org/project/_git/repo/pullrequest/42",
};
const GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {
icon: "change-request",
providerName: "source control",
shortName: "change request",
longName: "change request",
pluralLongName: "change requests",
providerLongName: "change request",
checkoutCommandExample: "123",
urlExample: "#42",
};
export function resolveChangeRequestPresentation(
provider: SourceControlProviderInfo | null | undefined,
): ChangeRequestPresentation {
switch (provider?.kind) {
case "github":
case undefined:
return GITHUB_CHANGE_REQUEST_PRESENTATION;
case "gitlab":
return GITLAB_CHANGE_REQUEST_PRESENTATION;
case "azure-devops":
return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;
case "unknown":
return GENERIC_CHANGE_REQUEST_PRESENTATION;
}
}
export function formatChangeRequestAction(
verb: "View" | "Create",
presentation: ChangeRequestPresentation,
): string {
return `${verb} ${presentation.shortName}`;
}
export function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {
return `create ${presentation.shortName}`;
}
+67
View File
@@ -0,0 +1,67 @@
import type { VcsDriverKind } from "@t3tools/contracts";
export interface VcsTerms {
readonly systemName: string;
readonly repositoryNoun: string;
readonly refNoun: string;
readonly refNounPlural: string;
readonly currentRefFallback: string;
}
export interface VcsActionPresentation {
readonly supportsGitWorkflowActions: boolean;
readonly unsupportedGitWorkflowDescription: string;
}
const gitLikeTerms: VcsTerms = {
systemName: "Git",
repositoryNoun: "repository",
refNoun: "branch",
refNounPlural: "branches",
currentRefFallback: "checkout",
};
const unknownTerms: VcsTerms = {
systemName: "VCS",
repositoryNoun: "repository",
refNoun: "ref",
refNounPlural: "refs",
currentRefFallback: "checkout",
};
export function resolveVcsTerms(kind: VcsDriverKind | null | undefined): VcsTerms {
if (kind === "jj") {
return {
systemName: "JJ",
repositoryNoun: "workspace",
refNoun: "bookmark",
refNounPlural: "bookmarks",
currentRefFallback: "working copy",
};
}
if (kind === "sapling") {
return {
...gitLikeTerms,
systemName: "Sapling",
};
}
if (kind === "git") {
return gitLikeTerms;
}
return unknownTerms;
}
export function resolveVcsActionPresentation(
kind: VcsDriverKind | null | undefined,
): VcsActionPresentation {
const terms = resolveVcsTerms(kind);
const supportsGitWorkflowActions = kind === undefined || kind === null || kind === "git";
return {
supportsGitWorkflowActions,
unsupportedGitWorkflowDescription: `Git commit, push, and PR actions are not available for this ${terms.systemName} ${terms.repositoryNoun}.`,
};
}
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more