fix(agentctl): keep comparison target Git non-interactive (#3185)

This commit is contained in:
Carlos Florêncio
2026-08-31 12:28:13 +00:00
committed by GitHub
parent 1c7b5afce1
commit 4b420f4950
18 changed files with 1574 additions and 63 deletions
@@ -24,8 +24,8 @@ import (
const freshMultiStatusPath = "/api/v1/git/status/multi?fresh=true"
func TestGitStatusMultiFreshCoalescesOverlappingHTTPRequests(t *testing.T) {
server, repoNames := newMultiRepoStatusServer(t)
gate := newGitStatusCommandGate(t)
server, repoNames := newMultiRepoStatusServerWithAgentEnv(t, append([]string(nil), os.Environ()...))
router := server.Router()
firstResult := make(chan gitStatusHTTPResult, 1)
@@ -17,6 +17,10 @@ import (
// reaches for a symbol defined only in the tagged one.
func newMultiRepoStatusServer(t *testing.T) (*Server, []string) {
return newMultiRepoStatusServerWithAgentEnv(t, nil)
}
func newMultiRepoStatusServerWithAgentEnv(t *testing.T, agentEnv []string) (*Server, []string) {
t.Helper()
taskRoot := t.TempDir()
repoNames := []string{"alpha", "beta"}
@@ -24,7 +28,10 @@ func newMultiRepoStatusServer(t *testing.T) (*Server, []string) {
newStatusTestRepo(t, taskRoot, repo)
}
log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error"})
cfg := &config.InstanceConfig{WorkDir: taskRoot}
cfg := &config.InstanceConfig{
WorkDir: taskRoot,
AgentEnv: append([]string(nil), agentEnv...),
}
return NewServer(cfg, process.NewManager(cfg, log), nil, nil, log), repoNames
}
@@ -0,0 +1,206 @@
package instance
import (
"context"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/kandev/kandev/internal/agentctl/server/config"
"github.com/kandev/kandev/internal/agentctl/server/process"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/pkg/agent"
)
const instanceComparisonGitShimModeEnv = "KANDEV_TEST_INSTANCE_COMPARISON_GIT_SHIM_MODE"
func init() {
if os.Getenv(instanceComparisonGitShimModeEnv) == "instance" {
runInstanceComparisonGitShim()
}
}
func TestCreateInstanceDoesNotWaitForComparisonTarget(t *testing.T) {
isolateInstanceTestGitEnv(t)
repoDir := createInstanceTestRepo(t)
startedMarker := filepath.Join(t.TempDir(), "comparison.started")
shimDir := installInstanceComparisonGitShim(t, startedMarker)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
log := newTestLogger(t)
mgr := NewManager(&config.Config{
Ports: config.PortConfig{Base: 0, Max: 0},
Defaults: config.InstanceDefaults{Protocol: agent.ProtocolACP},
}, log)
t.Cleanup(func() { _ = mgr.Shutdown(context.Background()) })
mgr.SetServerFactory(func(_ *config.InstanceConfig, _ *process.Manager, _ *logger.Logger) http.Handler {
return http.NotFoundHandler()
})
resultCh := make(chan struct {
response *CreateResponse
err error
}, 1)
started := time.Now()
go func() {
response, err := mgr.CreateInstance(context.Background(), &CreateRequest{
ID: "comparison-target-startup",
WorkspacePath: repoDir,
ComparisonTargets: map[string]models.ComparisonTarget{
"": instanceComparisonTestTarget(),
},
})
resultCh <- struct {
response *CreateResponse
err error
}{response: response, err: err}
}()
var result struct {
response *CreateResponse
err error
}
select {
case result = <-resultCh:
if result.err != nil {
t.Fatalf("CreateInstance: %v", result.err)
}
if elapsed := time.Since(started); elapsed >= 5*time.Second {
t.Fatalf("CreateInstance took %v, want it to return before comparison-target Git work completes", elapsed)
}
case <-time.After(5 * time.Second):
t.Fatal("CreateInstance waited for comparison-target Git work")
}
if result.response == nil {
t.Fatal("CreateInstance returned a nil response")
}
t.Cleanup(func() { _ = mgr.StopInstance(context.Background(), result.response.ID) })
waitForInstanceFile(t, startedMarker)
}
func isolateInstanceTestGitEnv(t *testing.T) {
t.Helper()
for _, key := range []string{
"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE",
"GIT_AUTHOR_DATE", "GIT_COMMITTER_DATE",
} {
value, present := os.LookupEnv(key)
if !present {
continue
}
if err := os.Unsetenv(key); err != nil {
t.Fatalf("unset %s: %v", key, err)
}
t.Cleanup(func() { _ = os.Setenv(key, value) })
}
}
func createInstanceTestRepo(t *testing.T) string {
t.Helper()
dir := t.TempDir()
runInstanceTestGit(t, dir, "init", "-b", "main")
runInstanceTestGit(t, dir, "config", "user.email", "test@example.com")
runInstanceTestGit(t, dir, "config", "user.name", "Test User")
runInstanceTestGit(t, dir, "commit", "--allow-empty", "-m", "initial")
return dir
}
func runInstanceTestGit(t *testing.T, dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
if output, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, output)
}
}
func installInstanceComparisonGitShim(t *testing.T, startedMarker string) string {
t.Helper()
dir := t.TempDir()
shimName := "git"
if runtime.GOOS == "windows" {
shimName += ".exe"
}
shim := filepath.Join(dir, shimName)
executable, err := os.Executable()
if err != nil {
t.Fatalf("find test executable: %v", err)
}
contents, err := os.ReadFile(executable)
if err != nil {
t.Fatalf("read test executable: %v", err)
}
if err := os.WriteFile(shim, contents, 0o755); err != nil {
t.Fatalf("write Git shim: %v", err)
}
if runtime.GOOS != "windows" {
if err := os.Chmod(shim, 0o755); err != nil {
t.Fatalf("make Git shim executable: %v", err)
}
}
t.Setenv(instanceComparisonGitShimModeEnv, "instance")
t.Setenv("KANDEV_TEST_COMPARISON_STARTED", startedMarker)
return dir
}
func runInstanceComparisonGitShim() {
args := os.Args[1:]
if len(args) < 2 {
os.Exit(0)
}
switch args[0] + " " + args[1] {
case "rev-parse --git-dir":
_, _ = os.Stdout.WriteString(".git\n")
case "remote get-url":
if marker := os.Getenv("KANDEV_TEST_COMPARISON_STARTED"); marker != "" {
_ = os.WriteFile(marker, nil, 0o600)
}
time.Sleep(15 * time.Second)
os.Exit(1)
case "rev-parse --verify":
_, _ = os.Stdout.WriteString("0123456789abcdef0123456789abcdef01234567\n")
}
os.Exit(0)
}
func waitForInstanceFile(t *testing.T, path string) {
t.Helper()
ticker := time.NewTicker(5 * time.Millisecond)
defer ticker.Stop()
timeout := time.NewTimer(20 * time.Second)
defer timeout.Stop()
for {
if _, err := os.Stat(path); err == nil {
return
}
select {
case <-ticker.C:
case <-timeout.C:
t.Fatalf("timed out waiting for %s", path)
}
}
}
func instanceComparisonTestTarget() models.ComparisonTarget {
return models.ComparisonTarget{
Version: models.ComparisonTargetVersion,
Provider: models.ComparisonTargetProviderGitHub,
Kind: models.ComparisonTargetKindPullRequest,
Number: 1154,
HeadBranch: "feature/cursor-cost",
TargetBranch: "main",
HeadRepository: models.ComparisonTargetRepository{
Host: "github.com", Path: "contributor/widget", ProviderID: "head-42",
RemoteURL: "https://github.com/contributor/widget.git",
},
TargetRepository: models.ComparisonTargetRepository{
Host: "github.com", Path: "upstream/widget", ProviderID: "base-99",
RemoteURL: "https://github.com/upstream/widget.git",
},
}
}
@@ -179,6 +179,20 @@ type Manager struct {
// from branch-only overrides. Updating one target must not race tracker
// creation or rewrite siblings' authoritative state.
comparisonTargetsMu sync.RWMutex
// trackerGitEnv is the process manager's detached snapshot of the instance
// environment used by workspace trackers. Each tracker receives its own
// copy so tracker-local changes cannot affect another tracker.
trackerGitEnv []string
trackerGitEnvMu sync.RWMutex
// comparisonTargetOps tracks one cancellable materialization per
// repository scope. The wait group lets teardown observe all operations
// that were admitted before shutdown.
comparisonTargetOps map[string]*comparisonTargetOperation
comparisonTargetOpsMu sync.Mutex
comparisonTargetOpsWG sync.WaitGroup
comparisonTargetOpsStopping bool
comparisonTargetOpsPermanent bool
// streamSubscribers tracks every workspace-stream subscriber attached
// via SubscribeWorkspaceStream so RescanRepositories can wire new
@@ -282,6 +296,14 @@ func (m *Manager) admitStart() (func(), error) {
// CloseAdmission rejects new process owners without waiting for in-flight
// handlers. Instance teardown calls it before shutting down HTTP.
func (m *Manager) CloseAdmission() {
m.comparisonTargetOpsMu.Lock()
m.comparisonTargetOpsStopping = true
m.comparisonTargetOpsPermanent = true
for _, operation := range m.comparisonTargetOps {
operation.cancel()
}
m.comparisonTargetOpsMu.Unlock()
m.admissionMu.Lock()
m.stopping = true
lifetimeCancel := m.lifetimeCancel
@@ -353,6 +375,7 @@ func NewManager(cfg *config.InstanceConfig, log *logger.Logger) *Manager {
lifetimeCtx: lifetimeCtx,
lifetimeCancel: lifetimeCancel,
workspaceSourceRoots: canonicalWorkspaceSourceRoots(cfg.WorkspaceSourceRoots),
trackerGitEnv: append([]string(nil), cfg.AgentEnv...),
}
// Build the root plus any immediate sibling repositories and recursively
// declared initialized submodules. The root remains a real empty-named
@@ -715,9 +738,9 @@ func (m *Manager) GetWorkspaceTrackerFor(subpath string) (*WorkspaceTracker, err
if t, ok := m.workspaceTrackersBySubpath[cleaned]; ok {
return t, nil
}
t := NewWorkspaceTracker(full, m.logger)
t := NewWorkspaceTrackerForRepo(full, cleaned, m.logger)
m.configureTracker(t, cleaned, m.currentWorkspaceSourceRoots())
m.prepareTrackerComparisonTarget(context.Background(), t)
m.prepareTrackerComparisonTarget(t)
m.workspaceTrackersBySubpath[cleaned] = t
return t, nil
}
@@ -898,7 +921,9 @@ func (m *Manager) findRepositoryTracker(repositoryName string) *WorkspaceTracker
// otherwise sit at its construction default and be demoted by the grace timer
// 60s later, while the user is looking at it.
func (m *Manager) newTrackerForRepo(path, repositoryName string) *WorkspaceTracker {
return NewWorkspaceTrackerForRepo(path, repositoryName, m.logger)
tracker := NewWorkspaceTrackerForRepo(path, repositoryName, m.logger)
tracker.SetGitEnvironment(m.trackerGitEnvironment())
return tracker
}
// applyWorkspacePollModeLocked gives newly built trackers the last mode the
@@ -1049,6 +1074,27 @@ func (m *Manager) gitEnvironment() []string {
return append([]string(nil), m.cfg.AgentEnv...)
}
func (m *Manager) trackerGitEnvironment() []string {
m.trackerGitEnvMu.RLock()
defer m.trackerGitEnvMu.RUnlock()
return append([]string(nil), m.trackerGitEnv...)
}
func (m *Manager) setTrackerGitEnvironment(env []string) {
detached := append([]string(nil), env...)
m.trackerGitEnvMu.Lock()
m.trackerGitEnv = detached
m.trackerGitEnvMu.Unlock()
root, trackers := m.snapshotTrackers()
if root != nil {
root.SetGitEnvironment(detached)
}
for _, tracker := range trackers {
tracker.SetGitEnvironment(detached)
}
}
// resolveSubpath normalises and validates a repo subpath relative to
// cfg.WorkDir. Returns ("", "", nil) for the root (empty/"."); otherwise
// returns the cleaned relative path and the absolute full path.
@@ -1350,6 +1396,7 @@ func (m *Manager) buildAdapterConfig() error {
if m.adapterCfg.OneShotConfig != nil {
m.adapterCfg.OneShotConfig.Env = m.cfg.AgentEnv
}
m.setTrackerGitEnvironment(m.cfg.AgentEnv)
return nil
}
@@ -1822,6 +1869,10 @@ func (m *Manager) stop(ctx context.Context) error {
// Stop trackers before the status guard: passthrough never calls Start() so the early return below would otherwise leak them.
m.stopWorkspaceTrackers()
comparisonStopErr, comparisonTargetsDrained := m.stopComparisonTargetOperations(ctx)
if comparisonTargetsDrained {
defer m.reopenComparisonTargetOperations()
}
status := m.Status()
if status == StatusStopped || status == StatusStopping {
@@ -1837,18 +1888,18 @@ func (m *Manager) stop(ctx context.Context) error {
// after a normal stop, in which case behaviour is unchanged.
tornDown := m.closeAdapterAndStdin()
if err := m.stopShellAndProcesses(ctx); err != nil {
return err
return errors.Join(comparisonStopErr, err)
}
switch {
case m.mainReapPending.Load():
if err := m.waitForProcessExit(ctx); err != nil {
return err
return errors.Join(comparisonStopErr, err)
}
m.mainReapPending.Store(false)
case tornDown:
m.drainAfterLateTeardown(ctx)
}
return nil
return comparisonStopErr
}
return nil
}
@@ -1861,7 +1912,7 @@ func (m *Manager) stop(ctx context.Context) error {
zap.String("protocol", m.agentProtocol()))
m.status.Store(StatusStopping)
auxiliaryStopErr := m.stopShellAndProcesses(ctx)
auxiliaryStopErr := errors.Join(comparisonStopErr, m.stopShellAndProcesses(ctx))
m.closeAdapterAndStdin()
m.killProcessGroupIfRequired()
mainStopErr := m.waitForProcessExit(ctx)
@@ -3,9 +3,9 @@ package process
import (
"context"
"errors"
"sync"
"time"
"github.com/kandev/kandev/internal/agentctl/server/config"
"github.com/kandev/kandev/internal/task/models"
"go.uber.org/zap"
)
@@ -38,23 +38,24 @@ func (m *Manager) getComparisonTargets() map[string]models.ComparisonTarget {
return result
}
// PrepareComparisonTargets materializes all desired targets before tracker
// polling starts. A failed target becomes explicitly unavailable; it never
// becomes an implicit origin/local comparison.
func (m *Manager) PrepareComparisonTargets(ctx context.Context) {
// PrepareComparisonTargets schedules materialization for all desired targets
// before tracker polling starts. A failed target becomes explicitly
// unavailable; it never becomes an implicit origin/local comparison.
func (m *Manager) PrepareComparisonTargets(_ context.Context) {
root, trackers := m.snapshotTrackers()
if root != nil {
m.prepareTrackerComparisonTarget(ctx, root)
m.prepareTrackerComparisonTarget(root)
}
for _, tracker := range trackers {
m.prepareTrackerComparisonTarget(ctx, tracker)
m.prepareTrackerComparisonTarget(tracker)
}
}
// UpdateComparisonTargets replaces the desired map and refreshes only trackers
// whose target changed. Existing ready siblings keep their state and are not
// refetched when another repository is updated.
func (m *Manager) UpdateComparisonTargets(ctx context.Context, targets map[string]models.ComparisonTarget) {
// refetched when another repository is updated. Target materialization runs in
// the manager lifetime, not in the request context.
func (m *Manager) UpdateComparisonTargets(_ context.Context, targets map[string]models.ComparisonTarget) {
previous := m.getComparisonTargets()
m.comparisonTargetsMu.Lock()
if len(targets) == 0 {
@@ -74,9 +75,8 @@ func (m *Manager) UpdateComparisonTargets(ctx context.Context, targets map[strin
if tracker == nil || comparisonTargetMapsEqual(previous, current, tracker.RepositoryName()) {
continue
}
m.prepareTrackerComparisonTarget(ctx, tracker)
m.prepareTrackerComparisonTarget(tracker)
}
go m.refreshComparisonTrackersDetached(all)
}
func comparisonTargetMapsEqual(previous, current map[string]models.ComparisonTarget, key string) bool {
@@ -85,47 +85,207 @@ func comparisonTargetMapsEqual(previous, current map[string]models.ComparisonTar
return leftOK == rightOK && (!leftOK || left.Equal(right))
}
func (m *Manager) prepareTrackerComparisonTarget(ctx context.Context, tracker *WorkspaceTracker) {
func (m *Manager) prepareTrackerComparisonTarget(tracker *WorkspaceTracker) {
if tracker == nil {
return
}
repositoryName := tracker.RepositoryName()
target := m.comparisonTargetFor(repositoryName)
if !m.comparisonTargetIsCurrent(repositoryName, target) {
previousResolution := tracker.ComparisonResolution()
if !m.setComparisonTargetIfCurrent(tracker, repositoryName, target) {
return
}
tracker.SetComparisonTarget(target)
if target != nil || previousResolution.Explicit {
m.refreshComparisonTrackerDetached(tracker)
}
if target == nil {
m.cancelComparisonTargetOperation(repositoryName)
return
}
if tracker.gitIndexPath == "" {
if !m.comparisonTargetIsCurrent(repositoryName, target) {
if tracker.gitIndexPath == "" || target.Validate() != nil {
m.cancelComparisonTargetOperation(repositoryName)
if m.setComparisonTargetUnavailableIfCurrent(tracker, repositoryName, target, comparisonTargetErrorInvalid) {
m.refreshComparisonTrackerDetached(tracker)
}
return
}
m.scheduleComparisonTargetOperation(repositoryName, tracker, *target)
}
func (m *Manager) scheduleComparisonTargetOperation(
repositoryName string,
tracker *WorkspaceTracker,
target models.ComparisonTarget,
) {
m.comparisonTargetOpsMu.Lock()
if m.comparisonTargetOpsStopping {
m.comparisonTargetOpsMu.Unlock()
return
}
operationCtx, release, err := m.beginComparisonTargetOperation()
if err != nil {
m.comparisonTargetOpsMu.Unlock()
return
}
operationCtx, cancel := context.WithTimeout(operationCtx, gitCommandTimeout)
operation := &comparisonTargetOperation{target: target, tracker: tracker, cancel: cancel}
if !m.comparisonTargetIsCurrent(repositoryName, &target) {
m.comparisonTargetOpsMu.Unlock()
cancel()
release()
return
}
if existing := m.comparisonTargetOps[repositoryName]; existing != nil {
if existing.tracker == tracker && existing.target.Equal(target) {
m.comparisonTargetOpsMu.Unlock()
cancel()
release()
return
}
tracker.SetComparisonTargetUnavailable(target, comparisonTargetErrorInvalid)
return
existing.cancel()
}
if m.comparisonTargetOps == nil {
m.comparisonTargetOps = make(map[string]*comparisonTargetOperation)
}
m.comparisonTargetOps[repositoryName] = operation
m.comparisonTargetOpsWG.Add(1)
m.comparisonTargetOpsMu.Unlock()
go m.runComparisonTargetOperation(repositoryName, operation, operationCtx, release)
}
type comparisonTargetOperation struct {
target models.ComparisonTarget
tracker *WorkspaceTracker
cancel context.CancelFunc
}
func (m *Manager) beginComparisonTargetOperation() (context.Context, func(), error) {
if m.lifetimeCtx == nil {
ctx, cancel := context.WithCancel(context.Background())
return ctx, cancel, nil
}
return m.BeginOwnedOperation(m.lifetimeCtx)
}
func (m *Manager) runComparisonTargetOperation(
repositoryName string,
operation *comparisonTargetOperation,
ctx context.Context,
release func(),
) {
defer m.comparisonTargetOpsWG.Done()
defer release()
defer operation.cancel()
defer func() {
m.comparisonTargetOpsMu.Lock()
if m.comparisonTargetOps[repositoryName] == operation {
delete(m.comparisonTargetOps, repositoryName)
}
m.comparisonTargetOpsMu.Unlock()
}()
runner := func(runCtx context.Context, args ...string) (string, error) {
output, err := tracker.runGitOutput(runCtx, args...)
output, err := operation.tracker.runGitOutput(runCtx, args...)
return string(output), err
}
materialized, err := materializeComparisonTarget(ctx, runner, *target)
materialized, err := materializeComparisonTarget(ctx, runner, operation.target)
if err != nil {
if !m.comparisonTargetIsCurrent(repositoryName, target) {
code := comparisonTargetErrorCode(err)
if !m.publishComparisonTargetUnavailable(repositoryName, operation, code) {
return
}
code := comparisonTargetErrorCode(err)
tracker.SetComparisonTargetUnavailable(target, code)
m.refreshComparisonTrackerDetached(operation.tracker)
m.logger.Warn("comparison target unavailable",
zap.String("repository", repositoryName),
zap.String("error_code", code),
zap.Error(err))
return
}
if !m.comparisonTargetIsCurrent(repositoryName, target) {
if !m.publishComparisonTargetReady(repositoryName, operation, materialized.Ref) {
return
}
tracker.SetComparisonTargetReady(target, materialized.Ref)
m.refreshComparisonTrackerDetached(operation.tracker)
}
func (m *Manager) setComparisonTargetUnavailableIfCurrent(
tracker *WorkspaceTracker,
repositoryName string,
target *models.ComparisonTarget,
code string,
) bool {
m.comparisonTargetsMu.RLock()
defer m.comparisonTargetsMu.RUnlock()
if !comparisonTargetMatches(m.cfg, repositoryName, target) {
return false
}
tracker.SetComparisonTargetUnavailable(target, code)
return true
}
func (m *Manager) setComparisonTargetIfCurrent(
tracker *WorkspaceTracker,
repositoryName string,
target *models.ComparisonTarget,
) bool {
m.comparisonTargetsMu.RLock()
defer m.comparisonTargetsMu.RUnlock()
if !comparisonTargetMatches(m.cfg, repositoryName, target) {
return false
}
tracker.SetComparisonTarget(target)
return true
}
func (m *Manager) publishComparisonTargetReady(
repositoryName string,
operation *comparisonTargetOperation,
ref string,
) bool {
m.comparisonTargetOpsMu.Lock()
defer m.comparisonTargetOpsMu.Unlock()
m.comparisonTargetsMu.RLock()
defer m.comparisonTargetsMu.RUnlock()
if m.comparisonTargetOps[repositoryName] != operation ||
!comparisonTargetMatches(m.cfg, repositoryName, &operation.target) {
return false
}
operation.tracker.SetComparisonTargetReady(&operation.target, ref)
return true
}
func (m *Manager) publishComparisonTargetUnavailable(
repositoryName string,
operation *comparisonTargetOperation,
code string,
) bool {
m.comparisonTargetOpsMu.Lock()
defer m.comparisonTargetOpsMu.Unlock()
m.comparisonTargetsMu.RLock()
defer m.comparisonTargetsMu.RUnlock()
if m.comparisonTargetOps[repositoryName] != operation ||
!comparisonTargetMatches(m.cfg, repositoryName, &operation.target) {
return false
}
operation.tracker.SetComparisonTargetUnavailable(&operation.target, code)
return true
}
func comparisonTargetMatches(
cfg *config.InstanceConfig,
repositoryName string,
target *models.ComparisonTarget,
) bool {
if cfg == nil || cfg.ComparisonTargets == nil {
return target == nil
}
current, ok := cfg.ComparisonTargets[repositoryName]
if target == nil {
return !ok
}
return ok && current.Equal(*target)
}
func (m *Manager) comparisonTargetIsCurrent(repositoryName string, target *models.ComparisonTarget) bool {
@@ -144,19 +304,54 @@ func comparisonTargetErrorCode(err error) string {
return comparisonTargetErrorRemoteSetup
}
func (m *Manager) refreshComparisonTrackersDetached(trackers []*WorkspaceTracker) {
var group sync.WaitGroup
for _, tracker := range trackers {
if tracker == nil {
continue
}
group.Add(1)
go func(tracker *WorkspaceTracker) {
defer group.Done()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
tracker.RefreshGitStatus(ctx)
}(tracker)
func (m *Manager) refreshComparisonTrackerDetached(tracker *WorkspaceTracker) {
if tracker == nil {
return
}
group.Wait()
go func() {
ctx := tracker.cancelCtx
if ctx == nil {
ctx = context.Background()
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
tracker.RefreshGitStatus(ctx)
}()
}
func (m *Manager) cancelComparisonTargetOperation(repositoryName string) {
m.comparisonTargetOpsMu.Lock()
if operation := m.comparisonTargetOps[repositoryName]; operation != nil {
operation.cancel()
}
m.comparisonTargetOpsMu.Unlock()
}
func (m *Manager) stopComparisonTargetOperations(ctx context.Context) (error, bool) {
m.comparisonTargetOpsMu.Lock()
m.comparisonTargetOpsStopping = true
for _, operation := range m.comparisonTargetOps {
operation.cancel()
}
m.comparisonTargetOpsMu.Unlock()
done := make(chan struct{})
go func() {
m.comparisonTargetOpsWG.Wait()
close(done)
}()
select {
case <-done:
return nil, true
case <-ctx.Done():
return ctx.Err(), false
}
}
func (m *Manager) reopenComparisonTargetOperations() {
m.comparisonTargetOpsMu.Lock()
if !m.comparisonTargetOpsPermanent {
m.comparisonTargetOpsStopping = false
}
m.comparisonTargetOpsMu.Unlock()
}
@@ -0,0 +1,424 @@
package process
import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/kandev/kandev/internal/agentctl/server/config"
"github.com/kandev/kandev/internal/task/models"
)
const (
comparisonTargetGitShimModeEnv = "KANDEV_TEST_COMPARISON_GIT_SHIM_MODE"
comparisonTargetCallTimeout = 15 * time.Second
)
func init() {
if os.Getenv(comparisonTargetGitShimModeEnv) == "comparison" {
runComparisonTargetGitShim()
}
}
func TestComparisonTargetPreparationNonBlocking(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
target := comparisonTargetProcessTestTarget()
gate := filepath.Join(t.TempDir(), "fetch.gate")
mgr, markers := newComparisonTargetTestManager(t, repoDir, target, map[string]string{
"KANDEV_TEST_FETCH_GATE": gate,
})
t.Cleanup(func() { _ = os.WriteFile(gate, nil, 0o600) })
done := make(chan struct{}, 1)
go func() {
mgr.PrepareComparisonTargets(context.Background())
close(done)
}()
waitForComparisonCall(t, done, "PrepareComparisonTargets")
resolution := mgr.GetWorkspaceTracker().ComparisonResolution()
if !resolution.Explicit || resolution.Status != comparisonTargetStatusUnavailable ||
resolution.ErrorCode != comparisonTargetErrorPending {
t.Fatalf("comparison resolution = %#v, want explicit pending state", resolution)
}
waitForComparisonFile(t, markers.fetchStarted)
if _, err := os.Stat(gate); err == nil {
t.Fatal("comparison fetch gate opened before PrepareComparisonTargets returned")
}
if err := os.WriteFile(gate, nil, 0o600); err != nil {
t.Fatalf("release comparison fetch: %v", err)
}
}
func TestComparisonTargetMaterializationPublishesReadyAndRefreshes(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
target := comparisonTargetProcessTestTarget()
mgr, markers := newComparisonTargetTestManager(t, repoDir, target, nil)
mgr.PrepareComparisonTargets(context.Background())
resolution := waitForComparisonResolution(t, mgr.GetWorkspaceTracker(), comparisonTargetStatusReady, "")
if resolution.Ref != target.ComparisonRef() {
t.Fatalf("comparison ref = %q, want %q", resolution.Ref, target.ComparisonRef())
}
waitForComparisonFile(t, markers.statusStarted)
}
func TestComparisonTargetMaterializationPublishesBoundedFetchFailureNoTransportFallback(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
target := comparisonTargetProcessTestTarget()
mgr, markers := newComparisonTargetTestManager(t, repoDir, target, map[string]string{
"KANDEV_TEST_FETCH_ERROR": "1",
})
mgr.PrepareComparisonTargets(context.Background())
resolution := waitForComparisonResolution(t, mgr.GetWorkspaceTracker(), comparisonTargetStatusUnavailable, comparisonTargetErrorFetch)
logBytes, err := os.ReadFile(markers.commandLog)
if err != nil {
t.Fatalf("read Git command log: %v", err)
}
log := string(logBytes)
if strings.Contains(log, "ssh://") || strings.Contains(log, "git@") || strings.Contains(log, " ssh ") {
t.Fatalf("comparison target attempted a transport fallback; commands:\n%s", log)
}
if got := strings.Count(log, "fetch --no-tags"); got != 1 {
t.Fatalf("comparison fetch count = %d, want one; commands:\n%s", got, log)
}
waitForComparisonFile(t, markers.statusStarted)
if resolution.Ref != "" {
t.Fatalf("failed comparison ref = %q, want empty", resolution.Ref)
}
}
func TestComparisonTargetPublicationRequiresActiveOperation(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
first := comparisonTargetProcessTestTarget()
second := first
second.TargetBranch = "develop"
mgr := NewManager(&config.InstanceConfig{
WorkDir: repoDir,
ComparisonTargets: map[string]models.ComparisonTarget{"": first},
}, newTestLogger(t))
t.Cleanup(func() { _ = mgr.StopForTeardown(context.Background()) })
tracker := mgr.GetWorkspaceTracker()
tracker.SetComparisonTarget(&first)
_, cancel := context.WithCancel(context.Background())
operation := &comparisonTargetOperation{target: first, tracker: tracker, cancel: cancel}
mgr.comparisonTargetOpsMu.Lock()
mgr.comparisonTargetOps = map[string]*comparisonTargetOperation{"": operation}
mgr.comparisonTargetOpsMu.Unlock()
mgr.comparisonTargetsMu.Lock()
mgr.cfg.ComparisonTargets[""] = second
mgr.comparisonTargetsMu.Unlock()
if mgr.publishComparisonTargetReady("", operation, first.ComparisonRef()) {
t.Fatal("superseded comparison operation published ready state")
}
resolution := tracker.ComparisonResolution()
if resolution.Status != comparisonTargetStatusUnavailable || resolution.ErrorCode != comparisonTargetErrorPending {
t.Fatalf("comparison resolution = %#v, want pending state", resolution)
}
}
func TestComparisonTargetUpdateSupersedesStaleOperation(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
first := comparisonTargetProcessTestTarget()
second := first
second.TargetBranch = "develop"
gate := filepath.Join(t.TempDir(), "fetch.gate")
mgr, markers := newComparisonTargetTestManager(t, repoDir, first, map[string]string{
"KANDEV_TEST_FETCH_GATE": gate,
})
mgr.PrepareComparisonTargets(context.Background())
waitForComparisonFile(t, markers.fetchStarted)
mgr.UpdateComparisonTargets(context.Background(), map[string]models.ComparisonTarget{"": second})
resolution := waitForComparisonResolution(t, mgr.GetWorkspaceTracker(), comparisonTargetStatusReady, "")
if resolution.Ref != second.ComparisonRef() {
t.Fatalf("comparison ref = %q, want latest target ref %q", resolution.Ref, second.ComparisonRef())
}
if snapshot := mgr.GetWorkspaceTracker().ComparisonTargetSnapshot(); snapshot == nil || !snapshot.Equal(second) {
t.Fatalf("comparison target snapshot = %#v, want latest target %#v", snapshot, second)
}
}
func TestComparisonTargetMaterializationCancellationOnShutdown(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
target := comparisonTargetProcessTestTarget()
gate := filepath.Join(t.TempDir(), "fetch.gate")
mgr, markers := newComparisonTargetTestManager(t, repoDir, target, map[string]string{
"KANDEV_TEST_FETCH_GATE": gate,
})
mgr.PrepareComparisonTargets(context.Background())
waitForComparisonFile(t, markers.fetchStarted)
started := time.Now()
if err := mgr.StopForTeardown(context.Background()); err != nil {
t.Fatalf("StopForTeardown: %v", err)
}
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("StopForTeardown took %v, want canceled materialization to stop promptly", elapsed)
}
}
func TestUpdateComparisonTargetsDoesNotWaitForMaterialization(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
target := comparisonTargetProcessTestTarget()
gate := filepath.Join(t.TempDir(), "fetch.gate")
mgr, markers := newComparisonTargetTestManager(t, repoDir, target, map[string]string{
"KANDEV_TEST_FETCH_GATE": gate,
})
mgr.UpdateComparisonTargets(context.Background(), nil)
done := make(chan struct{}, 1)
go func() {
mgr.UpdateComparisonTargets(context.Background(), map[string]models.ComparisonTarget{"": target})
close(done)
}()
waitForComparisonCall(t, done, "UpdateComparisonTargets")
waitForComparisonFile(t, markers.fetchStarted)
if resolution := mgr.GetWorkspaceTracker().ComparisonResolution(); resolution.ErrorCode != comparisonTargetErrorPending {
t.Fatalf("comparison resolution = %#v, want pending state", resolution)
}
if err := os.WriteFile(gate, nil, 0o600); err != nil {
t.Fatalf("release comparison fetch: %v", err)
}
}
func TestGetWorkspaceTrackerForDoesNotWaitForMaterialization(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
lazyDir := filepath.Join(repoDir, "lazy")
initGitRepoAt(t, lazyDir)
target := comparisonTargetProcessTestTarget()
gate := filepath.Join(t.TempDir(), "fetch.gate")
mgr, markers := newComparisonTargetTestManager(t, repoDir, target, map[string]string{
"KANDEV_TEST_FETCH_GATE": gate,
})
mgr.UpdateComparisonTargets(context.Background(), map[string]models.ComparisonTarget{"lazy": target})
resultCh := make(chan struct {
tracker *WorkspaceTracker
err error
}, 1)
go func() {
tracker, err := mgr.GetWorkspaceTrackerFor("lazy")
resultCh <- struct {
tracker *WorkspaceTracker
err error
}{tracker: tracker, err: err}
}()
var result struct {
tracker *WorkspaceTracker
err error
}
select {
case result = <-resultCh:
case <-time.After(comparisonTargetCallTimeout):
t.Fatal("timed out waiting for GetWorkspaceTrackerFor")
}
if result.err != nil {
t.Fatalf("GetWorkspaceTrackerFor: %v", result.err)
}
tracker := result.tracker
waitForComparisonFile(t, markers.fetchStarted)
resolution := tracker.ComparisonResolution()
if !resolution.Explicit || resolution.ErrorCode != comparisonTargetErrorPending {
t.Fatalf("lazy comparison resolution = %#v, want pending", resolution)
}
if err := os.WriteFile(gate, nil, 0o600); err != nil {
t.Fatalf("release comparison fetch: %v", err)
}
}
type comparisonTargetTestMarkers struct {
commandLog string
fetchStarted string
statusStarted string
}
func newComparisonTargetTestManager(
t *testing.T,
repoDir string,
target models.ComparisonTarget,
overrides map[string]string,
) (*Manager, comparisonTargetTestMarkers) {
t.Helper()
markers := comparisonTargetTestMarkers{
commandLog: filepath.Join(t.TempDir(), "commands.log"),
fetchStarted: filepath.Join(t.TempDir(), "fetch.started"),
statusStarted: filepath.Join(t.TempDir(), "status.started"),
}
instanceEnv := []string{
comparisonTargetGitShimModeEnv + "=comparison",
"KANDEV_TEST_GIT_LOG=" + markers.commandLog,
"KANDEV_TEST_FETCH_STARTED=" + markers.fetchStarted,
"KANDEV_TEST_STATUS_STARTED=" + markers.statusStarted,
}
for key, value := range overrides {
instanceEnv = append(instanceEnv, key+"="+value)
}
mgr := NewManager(&config.InstanceConfig{
WorkDir: repoDir,
AgentEnv: instanceEnv,
ComparisonTargets: map[string]models.ComparisonTarget{"": target},
}, newTestLogger(t))
t.Cleanup(func() { _ = mgr.StopForTeardown(context.Background()) })
shimDir := installComparisonTargetGitShim(t)
t.Setenv("PATH", shimDir+string(os.PathListSeparator)+os.Getenv("PATH"))
return mgr, markers
}
func installComparisonTargetGitShim(t *testing.T) string {
t.Helper()
return installComparisonTargetGitShimMode(t, "comparison")
}
func installComparisonTargetGitShimMode(t *testing.T, mode string) string {
t.Helper()
dir := t.TempDir()
shimName := "git"
if runtime.GOOS == "windows" {
shimName += ".exe"
}
shim := filepath.Join(dir, shimName)
executable, err := os.Executable()
if err != nil {
t.Fatalf("find test executable: %v", err)
}
contents, err := os.ReadFile(executable)
if err != nil {
t.Fatalf("read test executable: %v", err)
}
if err := os.WriteFile(shim, contents, 0o755); err != nil {
t.Fatalf("write Git shim: %v", err)
}
if runtime.GOOS != "windows" {
if err := os.Chmod(shim, 0o755); err != nil {
t.Fatalf("make Git shim executable: %v", err)
}
}
t.Setenv(comparisonTargetGitShimModeEnv, mode)
return dir
}
func runComparisonTargetGitShim() {
args := os.Args[1:]
if logPath := os.Getenv("KANDEV_TEST_GIT_LOG"); logPath != "" {
if file, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666); err == nil {
_, _ = fmt.Fprintln(file, strings.Join(args, " "))
_ = file.Close()
}
}
if len(args) < 2 {
os.Exit(0)
}
if args[0] == "config" && strings.HasPrefix(args[1], "remote.") {
os.Exit(0)
}
switch args[0] + " " + args[1] {
case "remote get-url":
os.Exit(1)
case "remote add":
os.Exit(0)
case "fetch --no-tags":
if os.Getenv("KANDEV_TEST_FETCH_ERROR") == "1" {
os.Exit(1)
}
joined := strings.Join(args, " ")
if strings.Contains(joined, "refs/heads/main:") {
touchComparisonTargetShimMarker("KANDEV_TEST_FETCH_STARTED")
waitForComparisonTargetShimGate()
}
case "rev-parse --git-dir":
_, _ = os.Stdout.WriteString(".git\n")
case "rev-parse --verify":
_, _ = os.Stdout.WriteString("0123456789abcdef0123456789abcdef01234567\n")
case "status --porcelain":
touchComparisonTargetShimMarker("KANDEV_TEST_STATUS_STARTED")
}
os.Exit(0)
}
func touchComparisonTargetShimMarker(envKey string) {
if path := os.Getenv(envKey); path != "" {
_ = os.WriteFile(path, nil, 0o600)
}
}
func waitForComparisonTargetShimGate() {
gate := os.Getenv("KANDEV_TEST_FETCH_GATE")
if gate == "" {
return
}
for {
if _, err := os.Stat(gate); err == nil {
return
}
time.Sleep(10 * time.Millisecond)
}
}
func waitForComparisonFile(t *testing.T, path string) {
t.Helper()
ticker := time.NewTicker(5 * time.Millisecond)
defer ticker.Stop()
timeout := time.NewTimer(comparisonTargetCallTimeout)
defer timeout.Stop()
for {
if _, err := os.Stat(path); err == nil {
return
}
select {
case <-ticker.C:
case <-timeout.C:
t.Fatalf("timed out waiting for %s", path)
}
}
}
func waitForComparisonCall(t *testing.T, done <-chan struct{}, operation string) {
t.Helper()
select {
case <-done:
case <-time.After(comparisonTargetCallTimeout):
t.Fatalf("timed out waiting for %s to return", operation)
}
}
func waitForComparisonResolution(
t *testing.T,
tracker *WorkspaceTracker,
wantStatus string,
wantErrorCode string,
) ComparisonResolution {
t.Helper()
ticker := time.NewTicker(5 * time.Millisecond)
defer ticker.Stop()
timeout := time.NewTimer(comparisonTargetCallTimeout)
defer timeout.Stop()
for {
resolution := tracker.ComparisonResolution()
if resolution.Status == wantStatus && (wantErrorCode == "" || resolution.ErrorCode == wantErrorCode) {
return resolution
}
select {
case <-ticker.C:
case <-timeout.C:
t.Fatalf("timed out waiting for comparison resolution %s/%s, last %#v", wantStatus, wantErrorCode, resolution)
}
}
}
@@ -190,7 +190,7 @@ func (m *Manager) transitionToMultiRepoMode(ctx context.Context, workDir string,
bareRoot := m.newTrackerForRepo(workDir, "")
m.configureTracker(bareRoot, "", roots)
m.prepareTrackerComparisonTarget(ctx, bareRoot)
m.prepareTrackerComparisonTarget(bareRoot)
bareRoot.Start(ctx)
for _, sub := range subs {
bareRoot.AttachWorkspaceStreamSubscriber(sub)
@@ -200,7 +200,7 @@ func (m *Manager) transitionToMultiRepoMode(ctx context.Context, workDir string,
for _, child := range children {
tracker := m.newTrackerForRepo(child.path, child.name)
m.configureTracker(tracker, child.name, roots)
m.prepareTrackerComparisonTarget(ctx, tracker)
m.prepareTrackerComparisonTarget(tracker)
tracker.Start(ctx)
for _, sub := range subs {
tracker.AttachWorkspaceStreamSubscriber(sub)
@@ -247,7 +247,7 @@ func (m *Manager) appendNewRepoTrackers(ctx context.Context, workDir string, chi
zap.String("path", child.path))
tracker := m.newTrackerForRepo(child.path, child.name)
m.configureTracker(tracker, child.name, roots)
m.prepareTrackerComparisonTarget(ctx, tracker)
m.prepareTrackerComparisonTarget(tracker)
tracker.Start(ctx)
for _, sub := range subs {
tracker.AttachWorkspaceStreamSubscriber(sub)
@@ -312,7 +312,7 @@ func (m *Manager) reconcileRepoTrackers(ctx context.Context, workDir string, chi
}
tracker := m.newTrackerForRepo(child.path, child.name)
m.configureTracker(tracker, child.name, roots)
m.prepareTrackerComparisonTarget(ctx, tracker)
m.prepareTrackerComparisonTarget(tracker)
tracker.Start(ctx)
for _, sub := range subs {
tracker.AttachWorkspaceStreamSubscriber(sub)
@@ -78,6 +78,7 @@ func (m *Manager) buildWorkspaceTrackerGraph(
}
func (m *Manager) configureTracker(tracker *WorkspaceTracker, repositoryName string, roots []string) {
tracker.SetGitEnvironment(m.trackerGitEnvironment())
tracker.SetAllowedSourceRoots(roots)
if !tracker.IsSubmodule() {
tracker.SetBaseBranch(lookupBaseBranch(m.getBaseBranches(), repositoryName))
@@ -123,7 +124,7 @@ func (m *Manager) reconcileWorkspaceTrackerGraph(
root = oldRoot
rootReused = true
syncTrackerConfiguration(root, desiredRoot, roots)
m.prepareTrackerComparisonTarget(ctx, root)
m.prepareTrackerComparisonTarget(root)
desiredRoot.Stop()
}
if !rootReused {
@@ -137,7 +138,7 @@ func (m *Manager) reconcileWorkspaceTrackerGraph(
identity := repositoryTrackerIdentity(desired.RepositoryName(), desired.workDir)
if existing := oldByIdentity[identity]; existing != nil {
syncTrackerConfiguration(existing, desired, roots)
m.prepareTrackerComparisonTarget(ctx, existing)
m.prepareTrackerComparisonTarget(existing)
desired.Stop()
retained = append(retained, existing)
used[existing] = struct{}{}
@@ -3,7 +3,6 @@ package process
import (
"bytes"
"context"
"os"
"os/exec"
"strings"
@@ -34,27 +33,130 @@ func gitWorkClass(ctx context.Context) subproc.GitWorkClass {
// See: https://git-scm.com/docs/git#Documentation/git.txt-codeGITOPTIONALLOCKSltbooleangtcode
const gitOptionalLocksOff = "GIT_OPTIONAL_LOCKS=0"
const defaultGitSSHCommand = "ssh -oBatchMode=yes"
// pollingGitCommand builds an exec.Cmd with optional Git locks disabled. The
// lock policy is independent from the admission class: fresh interactive
// status also needs lockless reads while still using the interactive queue.
func (wt *WorkspaceTracker) pollingGitCommand(ctx context.Context, args ...string) *exec.Cmd {
cmd := subproc.NewGitCommand(ctx, args...)
cmd.Dir = wt.workDir
cmd.Env = gitCommandEnv(ctx, true)
cmd.Env = wt.gitCommandEnv(ctx, true)
return cmd
}
func gitCommandEnv(ctx context.Context, lockless bool) []string {
env := os.Environ()
func (wt *WorkspaceTracker) gitCommandEnv(ctx context.Context, lockless bool) []string {
env := wt.gitEnvironmentSnapshot()
if lockless {
env = replaceGitEnvAssignment(env, gitOptionalLocksOff)
}
if indexPath := gitIndexFile(ctx); indexPath != "" {
env = replaceGitEnvAssignment(env, "GIT_INDEX_FILE="+indexPath)
}
for _, assignment := range []string{
"GIT_TERMINAL_PROMPT=0",
"GCM_INTERACTIVE=Never",
"GIT_ASKPASS=echo",
"SSH_ASKPASS=/bin/false",
} {
env = replaceGitEnvAssignment(env, assignment)
}
if command, ok := gitEnvValue(env, "GIT_SSH_COMMAND"); ok && strings.TrimSpace(command) != "" {
env = replaceGitEnvAssignment(env, "GIT_SSH_COMMAND="+forceGitSSHBatchMode(command))
} else {
env = replaceGitEnvAssignment(env, "GIT_SSH_COMMAND="+defaultGitSSHCommand)
}
return env
}
func gitEnvValue(env []string, key string) (string, bool) {
prefix := key + "="
var value string
found := false
for _, entry := range env {
if strings.HasPrefix(entry, prefix) {
value = strings.TrimPrefix(entry, prefix)
found = true
}
}
return value, found
}
// forceGitSSHBatchMode places BatchMode=yes immediately after a direct
// OpenSSH executable. OpenSSH uses the first command-line value for an option,
// so this prevents a later BatchMode=no in the inherited command from
// restoring terminal prompting while preserving the command's other options.
// Shell prefixes and custom wrappers are not parsed here. They use the safe
// default instead of receiving an option in the wrong position.
func forceGitSSHBatchMode(command string) string {
command = strings.TrimSpace(command)
if command == "" {
return defaultGitSSHCommand
}
commandEnd := shellWordEnd(command)
if commandEnd == 0 {
return defaultGitSSHCommand
}
executable, ok := shellWordValue(command[:commandEnd])
if !ok || !isOpenSSHExecutable(executable) {
return defaultGitSSHCommand
}
return command[:commandEnd] + " -oBatchMode=yes" + command[commandEnd:]
}
func shellWordValue(word string) (string, bool) {
if word == "" {
return "", false
}
if word[0] == '\'' || word[0] == '"' {
if len(word) < 2 || word[len(word)-1] != word[0] {
return "", false
}
return word[1 : len(word)-1], true
}
if strings.ContainsAny(word, "'\"") {
return "", false
}
return word, true
}
func isOpenSSHExecutable(executable string) bool {
lastSeparator := strings.LastIndexAny(executable, `/\`)
base := executable[lastSeparator+1:]
return base == "ssh" || base == "ssh.exe"
}
func shellWordEnd(command string) int {
var quote byte
escaped := false
for index := 0; index < len(command); index++ {
character := command[index]
if escaped {
escaped = false
continue
}
if quote != 0 {
if quote == '"' && character == '\\' {
escaped = true
continue
}
if character == quote {
quote = 0
}
continue
}
switch character {
case '\\':
escaped = true
case '\'', '"':
quote = character
case ' ', '\t', '\n', '\r':
return index
}
}
return len(command)
}
func replaceGitEnvAssignment(env []string, assignment string) []string {
key, _, ok := strings.Cut(assignment, "=")
if !ok {
@@ -79,7 +181,7 @@ func (wt *WorkspaceTracker) gitCommand(ctx context.Context, lockless bool, args
}
cmd := subproc.NewGitCommand(ctx, args...)
cmd.Dir = wt.workDir
cmd.Env = gitCommandEnv(ctx, false)
cmd.Env = wt.gitCommandEnv(ctx, false)
return cmd
}
@@ -0,0 +1,140 @@
package process
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/kandev/kandev/internal/agentctl/server/config"
)
func TestManagerTrackerGitEnvironmentUsesInstanceEnvironment(t *testing.T) {
t.Setenv("KANDEV_TEST_TRACKER_CREDENTIAL", "ambient-credential")
t.Setenv("KANDEV_TEST_AMBIENT_ONLY", "ambient-only")
t.Setenv("GIT_TERMINAL_PROMPT", "1")
t.Setenv("GCM_INTERACTIVE", "Always")
t.Setenv("GIT_ASKPASS", "ambient-askpass")
t.Setenv("SSH_ASKPASS", "ambient-ssh-askpass")
t.Setenv("GIT_SSH_COMMAND", "ambient-ssh")
instanceEnv := []string{
"KANDEV_TEST_TRACKER_CREDENTIAL=instance-credential",
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=http.extraheader",
"GIT_CONFIG_VALUE_0=Authorization: Bearer instance-token",
"GIT_TERMINAL_PROMPT=1",
"GCM_INTERACTIVE=Always",
"GIT_ASKPASS=instance-askpass",
"SSH_ASKPASS=instance-ssh-askpass",
}
mgr := NewManager(&config.InstanceConfig{
WorkDir: t.TempDir(),
AgentEnv: instanceEnv,
}, newTestLogger(t))
t.Cleanup(mgr.stopWorkspaceTrackers)
cmd := mgr.GetWorkspaceTracker().gitCommand(context.Background(), false, "status")
env := environmentMap(cmd.Env)
want := map[string]string{
"KANDEV_TEST_TRACKER_CREDENTIAL": "instance-credential",
"GIT_CONFIG_COUNT": "1",
"GIT_CONFIG_KEY_0": "http.extraheader",
"GIT_CONFIG_VALUE_0": "Authorization: Bearer instance-token",
"GIT_TERMINAL_PROMPT": "0",
"GCM_INTERACTIVE": "Never",
"GIT_ASKPASS": "echo",
"SSH_ASKPASS": "/bin/false",
"GIT_SSH_COMMAND": "ssh -oBatchMode=yes",
}
for key, wantValue := range want {
if got := env[key]; got != wantValue {
t.Errorf("%s = %q, want %q", key, got, wantValue)
}
}
if _, ok := env["KANDEV_TEST_AMBIENT_ONLY"]; ok {
t.Fatal("ambient tracker credential marker unexpectedly present")
}
if env["GIT_SSH_COMMAND"] == "ambient-ssh" {
t.Fatal("ambient SSH command unexpectedly reached tracker")
}
}
func TestWorkspaceGitEnvironmentForcesExplicitSSHBatchMode(t *testing.T) {
tracker := NewWorkspaceTracker(t.TempDir(), newTestLogger(t))
tracker.SetGitEnvironment([]string{
"GIT_SSH_COMMAND=ssh -i /instance/key -oBatchMode=no",
})
regular := environmentMap(tracker.gitCommand(context.Background(), false, "fetch").Env)
polling := environmentMap(tracker.pollingGitCommand(context.Background(), "status").Env)
for name, env := range map[string]map[string]string{
"regular": regular,
"polling": polling,
} {
want := "ssh -oBatchMode=yes -i /instance/key -oBatchMode=no"
if got := env["GIT_SSH_COMMAND"]; got != want {
t.Errorf("%s GIT_SSH_COMMAND = %q, want %q", name, got, want)
}
}
}
func TestForceGitSSHBatchModeSupportsDirectOpenSSHOnly(t *testing.T) {
tests := map[string]string{
"ssh -i /instance/key -oBatchMode=no": "ssh -oBatchMode=yes -i /instance/key -oBatchMode=no",
`'path with spaces/ssh' -i key`: `'path with spaces/ssh' -oBatchMode=yes -i key`,
`env FOO=bar ssh -i key`: defaultGitSSHCommand,
`FOO=bar ssh -i key`: defaultGitSSHCommand,
`exec ssh -i key`: defaultGitSSHCommand,
`plink -i key`: defaultGitSSHCommand,
}
for command, want := range tests {
if got := forceGitSSHBatchMode(command); got != want {
t.Errorf("forceGitSSHBatchMode(%q) = %q, want %q", command, got, want)
}
}
}
func TestWorkspaceGitEnvironmentSnapshotsAreDetached(t *testing.T) {
instanceEnv := []string{"KANDEV_TEST_TRACKER_VALUE=initial"}
workspace := t.TempDir()
if err := os.Mkdir(filepath.Join(workspace, "repo"), 0o755); err != nil {
t.Fatalf("mkdir repo: %v", err)
}
mgr := NewManager(&config.InstanceConfig{
WorkDir: workspace,
AgentEnv: instanceEnv,
}, newTestLogger(t))
t.Cleanup(mgr.stopWorkspaceTrackers)
root := mgr.GetWorkspaceTracker()
lazy, err := mgr.GetWorkspaceTrackerFor("repo")
if err != nil {
t.Fatalf("lazy tracker: %v", err)
}
instanceEnv[0] = "KANDEV_TEST_TRACKER_VALUE=source-mutated"
root.SetGitEnvironment([]string{"KANDEV_TEST_TRACKER_VALUE=root-only"})
if got := environmentMap(root.gitCommand(context.Background(), false, "status").Env)["KANDEV_TEST_TRACKER_VALUE"]; got != "root-only" {
t.Fatalf("root tracker value = %q, want root-only", got)
}
if got := environmentMap(lazy.gitCommand(context.Background(), false, "status").Env)["KANDEV_TEST_TRACKER_VALUE"]; got != "initial" {
t.Fatalf("lazy tracker value = %q, want initial", got)
}
}
func environmentMap(env []string) map[string]string {
result := make(map[string]string, len(env))
for _, entry := range env {
for i := 0; i < len(entry); i++ {
if entry[i] != '=' {
continue
}
result[entry[:i]] = entry[i+1:]
break
}
}
return result
}
@@ -47,6 +47,8 @@ type WorkspaceTracker struct {
workDir string
gitIndexPath string // Cached, validated path to git index file (works with worktrees)
logger *logger.Logger
gitEnv []string
gitEnvMu sync.RWMutex
// allowedSourceRoots are canonical roots of durable sources explicitly
// attached to this workspace. They are deliberately separate from workDir:
// a link may point outside the workspace, but only to one of these roots.
@@ -231,6 +233,22 @@ func (wt *WorkspaceTracker) RepositoryName() string {
return wt.repositoryName
}
// SetGitEnvironment stores a detached copy of the instance environment used
// for every Git command started by this tracker. Tracker-owned copies prevent
// a later manager or sibling-tracker update from changing an in-flight command.
func (wt *WorkspaceTracker) SetGitEnvironment(env []string) {
detached := append([]string(nil), env...)
wt.gitEnvMu.Lock()
wt.gitEnv = detached
wt.gitEnvMu.Unlock()
}
func (wt *WorkspaceTracker) gitEnvironmentSnapshot() []string {
wt.gitEnvMu.RLock()
defer wt.gitEnvMu.RUnlock()
return append([]string(nil), wt.gitEnv...)
}
// SetBaseBranch records the task's stored base branch for this repository.
// Called once after construction by the process manager; subsequent git
// status updates use this value as the first candidate when resolving
@@ -0,0 +1,56 @@
# ADR-2026-08-31-deterministic-noninteractive-git-transport: Keep Internal Git Transport Deterministic and Non-interactive
**Status:** accepted
**Date:** 2026-08-31
**Area:** backend, agentctl, protocol, security, operations
## Context
Kandev materializes repository-qualified comparison targets with Git. The target uses a canonical HTTPS URL. This work can occur during instance creation or a Git-status UI request.
The workspace tracker starts Git with the ambient agentctl environment. It does not use the instance environment that contains managed Git credentials. It also permits terminal prompts.
If HTTPS credentials are absent, Git can request a user name and password from the launcher terminal. The Git command then blocks instance readiness and the UI.
One possible repair retries the target through SSH after an HTTPS error. This retry can use a different identity, credential source, and host-trust policy. It can also start an SSH host-key or key-passphrase prompt.
## Decision
Kandev-owned Git network commands are non-interactive. They cannot read credentials, confirmation, or host-trust answers from the launcher terminal.
Each workspace tracker uses a detached copy of the instance's effective Git environment. The environment preserves managed credential-helper entries and direct OpenSSH command options. Kandev adds the established prompt controls and puts `BatchMode=yes` before inherited batch-mode options. Unsupported shell prefixes and wrappers use the safe non-interactive default. The existing command deadline remains in force.
Kandev selects one transport before it starts the command. An authentication or transport error does not cause an automatic retry through SSH, HTTPS, or another transport.
Repository-qualified comparison targets keep their canonical HTTPS URLs. A missing credential makes comparison data unavailable. It does not change `origin`, the checkout upstream, or push routing.
Comparison-target network work does not delay instance readiness or Git-status UI requests. The target remains pending and fail-closed until background materialization succeeds. The process-manager lifetime controls cancellation.
## Consequences
- A Git authentication error cannot capture the launcher terminal.
- Instance creation and Git-status UI requests do not wait for comparison-target network work.
- Managed HTTPS credentials can reach comparison-target commands through the instance environment.
- Explicit SSH configuration remains available for commands that already select SSH, with terminal prompting disabled.
- A user must select or configure another transport explicitly. Kandev does not guess after an error.
- Private comparison targets remain unavailable when the selected credential scope cannot read them.
## Alternatives considered
### Retry SSH after an HTTPS error
Rejected. The retry can change identity and host trust after the user selected a different transport. It can also create a second interactive prompt.
### Use only the host environment
Rejected. Remote executors and managed credentials use the instance environment. The host environment can contain unrelated credentials or no credentials.
### Keep materialization synchronous with prompts disabled
Rejected. Prompt suppression removes one unbounded wait. Network and credential-helper deadlines can still delay startup and UI requests.
## Related
- [ADR-2026-08-19-repository-qualified-comparison-targets](2026-08-19-repository-qualified-comparison-targets.md)
- [Workspace Git Status requirements](../specs/platform/requirements/workspace-git-status.md)
- [Workspace Git Status system design](../specs/platform/system-design/workspace-git-status.md)
+1
View File
@@ -190,6 +190,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-20-settings-prompt-editor-provider-ownership | [Settings Prompt Editors Own Monaco Completion Providers](2026-08-20-settings-prompt-editor-provider-ownership.md) | accepted | frontend | 2026-08-20 |
| 2026-08-14-kandev-native-agent-rich-output | [Keep Agent Rich Output Host Native](2026-08-14-kandev-native-agent-rich-output.md) | accepted | backend, frontend, protocol, security | 2026-08-14 |
| 2026-08-19-repository-qualified-comparison-targets | [Qualify Git Comparison Targets by Repository](2026-08-19-repository-qualified-comparison-targets.md) | accepted | backend, agentctl, frontend, protocol, GitHub, GitLab | 2026-08-19 |
| 2026-08-31-deterministic-noninteractive-git-transport | [Keep Internal Git Transport Deterministic and Non-interactive](2026-08-31-deterministic-noninteractive-git-transport.md) | accepted | backend, agentctl, protocol, security, operations | 2026-08-31 |
| 2026-08-20-startup-configuration-source-parity | [Startup Configuration Uses One Typed Source Model](2026-08-20-startup-configuration-source-parity.md) | accepted | backend, agentctl, frontend, cli, security, operations | 2026-08-20 |
| 2026-08-20-acp-client-non-underscore-extension-methods | [Route Non-Underscore Inbound Client Methods to the Extension Handler](2026-08-20-acp-client-non-underscore-extension-methods.md) | accepted | backend, protocol | 2026-08-20 |
| 2026-08-22-persistent-fork-approval-labels | [Persist Fork Approval Labels Across Pushes](2026-08-22-persistent-fork-approval-labels.md) | accepted (amended by 2026-08-24-unified-fork-approval-label) | infra, workflow, security | 2026-08-22 |
@@ -0,0 +1,101 @@
---
spec: docs/specs/platform/requirements/workspace-git-status.md
created: 2026-08-31
status: implemented
---
# Implementation Plan: Non-interactive Comparison-target Git
## Overview
Remove the password prompt that blocks Kandev startup after a comparison-target fetch. Workspace trackers will use the instance's Git environment and established non-interactive controls. Comparison-target network work will run outside instance readiness and Git-status request paths.
This plan implements `AC-PLATFORM-WORKSPACE-GIT-STATUS-001.16` through `.18`.
## Confirmed root cause
Release `v0.92.0` added repository-qualified comparison-target materialization. The regression remains in `v0.92.2` and current `main`.
The blocking path has three parts:
- `WorkspaceTracker.runGitOutput` uses `os.Environ()` instead of `InstanceConfig.AgentEnv`.
- The command environment does not enforce non-interactive Git controls.
- Instance creation and lazy tracker creation wait for comparison-target materialization.
As a result, Git can read a user name and password from the terminal that launched Kandev.
## Invariants
- Kandev-owned comparison-target commands never read the launcher terminal.
- Workspace trackers use the exact instance Git credential environment.
- Managed `GIT_CONFIG_*` credential-helper entries remain intact.
- Direct OpenSSH commands and their options remain intact. Kandev forces `BatchMode=yes` before inherited batch-mode options; unsupported shell prefixes and wrappers use the safe non-interactive default.
- Git command deadlines and throttle admission remain in force.
- A target is pending and fail-closed before its fetch starts.
- Instance readiness, live target updates, rescan, and lazy tracker creation do not wait for network Git.
- Manager shutdown cancels unfinished target work.
- An HTTPS error does not cause an automatic SSH retry.
- `origin`, the checkout upstream, and push routing do not change.
## Design
### Tracker Git environment
The process manager owns a detached copy of `InstanceConfig.AgentEnv`. It gives a separate copy to every tracker that it creates. This includes root, repository, submodule, rescan, and lazy trackers.
The tracker command helper composes this environment with the established non-interactive controls. It does not use the ambient agentctl environment. Test helpers can still create a tracker without an instance environment.
### Background target materialization
The process manager sets the selected target to pending before it schedules network work. One manager-owned background operation materializes each current repository target.
The operation uses the manager lifetime context and the existing Git-command deadline. A newer target replaces stale work. A stale result cannot overwrite the current target state.
On success, the manager publishes the exact comparison ref and starts a detached status refresh. On error, it publishes the existing bounded unavailable code. Callers receive control after scheduling the work.
### Transport policy
Comparison targets keep their canonical HTTPS URLs. The command uses the instance credential environment once. It does not construct or try an SSH URL after an HTTPS error.
The policy is recorded in [ADR: Keep Internal Git Transport Deterministic and Non-interactive](../../decisions/2026-08-31-deterministic-noninteractive-git-transport.md).
## Test strategy
- A Git shim records the command environment and proves that managed credential configuration reaches the tracker.
- The shim proves that prompt controls override interactive values.
- Tracker-graph tests cover root, repository, submodule, rescan, and lazy tracker creation.
- A blocking Git shim proves that instance preparation and lazy tracker lookup return before the fetch ends.
- State tests prove pending, ready, unavailable, stale-result rejection, and shutdown cancellation.
- Command tests prove that one HTTPS error does not start an SSH retry.
- The existing fork-PR browser scenario proves that the session opens while its target is unavailable.
## Execution order
[x] 1. [Task 01: Propagate the instance Git environment](task-01-propagate-instance-git-environment.md) (done)
[x] 2. [Task 02: Detach comparison-target materialization](task-02-detach-comparison-target-materialization.md) (done)
Task 02 depends on Task 01. Background commands must use the correct environment before they leave the request path.
Both work orders are implemented. Validation results are recorded in the work-order implementation records; the remaining delivery steps cover commit, PR creation, and post-PR fixup.
The first PR fixup also serialized comparison-target publication with active-operation identity, removed stale-result recursion, and forced direct OpenSSH commands into batch mode. The second PR fixup gates target admission during manager teardown and preserves adapter and shell cleanup when target shutdown reports an error. Portable lifecycle fixtures run on Windows as well as Unix, and their nonblocking assertions use closed fetch gates rather than wall-clock thresholds.
## Validation
```bash
cd apps/backend && go test ./internal/agentctl/server/process ./internal/agentctl/server/instance
make -C apps/backend lint
cd apps/web && pnpm e2e:run --host --no-build --project chromium -- e2e/tests/git/fork-pr-comparison-target.spec.ts
python3 scripts/lint-spec-files.test.py
python3 scripts/lint-spec-files.py --all
git diff --check
```
## Out of scope
- Automatic HTTPS-to-SSH fallback.
- A new private-repository credential scope.
- Changes to comparison-target identity or remote naming.
- Changes to the Git-status API or WebSocket payload.
- Changes to `origin`, upstream tracking, or push routing.
- New UI controls for Git credentials or transport selection.
@@ -0,0 +1,83 @@
---
id: "01-propagate-instance-git-environment"
title: "Propagate the instance Git environment"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/platform/requirements/workspace-git-status.md"
---
# Task 01: Propagate the instance Git environment
Make every workspace tracker use the instance's effective Git environment. Enforce non-interactive prompt controls without removing managed credentials or explicit SSH configuration.
## Red tests first
Add focused tests that prove these behaviors:
- a tracker Git shim receives managed `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_*`, and `GIT_CONFIG_VALUE_*` entries from `InstanceConfig.AgentEnv`
- the shim receives `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=Never`, `GIT_ASKPASS=echo`, and `SSH_ASKPASS=/bin/false`
- a direct OpenSSH `GIT_SSH_COMMAND` keeps its command and options while forcing `BatchMode=yes`; unsupported prefixes and wrappers use the safe non-interactive default
- `ssh -oBatchMode=yes` is present when the instance does not supply an SSH command
- an ambient credential value does not replace the instance value
- root, repository, submodule, rescan, and lazy trackers receive detached environment copies
- later mutation of the source slice or another tracker does not change a tracker's environment
Record the focused red command before production changes.
## Implementation
- Store a detached Git environment on `WorkspaceTracker`.
- Build the environment from `InstanceConfig.AgentEnv`, not `os.Environ()`.
- Add established prompt controls with last-value precedence.
- Preserve direct OpenSSH `GIT_SSH_COMMAND` options while placing `BatchMode=yes` before any inherited batch-mode option. Use the safe default for unsupported shell prefixes or wrappers, and add it when the variable is absent.
- Route `runGitOutput` and `runPollingGitOutput` through the same environment builder.
- Apply the environment in the process manager's central tracker configuration path.
- Cover trackers that the manager creates during rescan, reconciliation, submodule discovery, and lazy lookup.
- Keep direct test constructors compatible with an isolated default environment.
## Acceptance
- Comparison-target commands can use managed HTTPS credentials from the instance environment.
- Git, Git Credential Manager, and SSH cannot request terminal input.
- All manager-owned trackers use equivalent detached environments.
- Existing command timeout and throttle tests remain green.
## Likely files
- `apps/backend/internal/agentctl/server/process/workspace_tracker.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_cmd.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_cmd_test.go`
- `apps/backend/internal/agentctl/server/process/manager.go`
- `apps/backend/internal/agentctl/server/process/manager_rescan.go`
- `apps/backend/internal/agentctl/server/process/manager_submodules.go`
- `apps/backend/internal/agentctl/server/process/manager_rescan_test.go`
- `apps/backend/internal/agentctl/server/process/manager_submodule_test.go`
## Verification
```bash
cd apps/backend && go test ./internal/agentctl/server/process -run 'TestWorkspaceGitEnvironment|TestManagerTrackerGitEnvironment|TestRunGitOutput' -count=1
cd apps/backend && go test ./internal/agentctl/server/process
```
## Parallelism
`sequential`. Task 02 consumes the tracker environment contract.
## Output contract
Record the red and green commands. Record the final environment precedence and proof for each tracker creation path.
## Implementation record
- Red: `cd apps/backend && go test ./internal/agentctl/server/process -run 'TestWorkspaceGitEnvironment|TestManagerTrackerGitEnvironment|TestRunGitOutput' -count=1` failed because tracker commands used ambient credentials and prompt settings.
- Green: the same focused command passed 5 tests after the change; the full process package passed 752 tests before Task 02 and 787 tests across process and instance after the complete package change.
- Precedence: the manager snapshots `InstanceConfig.AgentEnv`; each tracker receives a detached copy; lockless and per-observation `GIT_INDEX_FILE` overlays are applied; non-interactive controls override inherited values; a direct OpenSSH command keeps its options with `BatchMode=yes` placed first, while unsupported command shapes and missing commands use the safe default.
- Coverage: root, repository, submodule, rescan, reconciliation, and lazy tracker construction all pass through `configureTracker` or `newTrackerForRepo`, which applies the manager snapshot before Git work starts.
## PR fixup record
- Review fix: direct OpenSSH commands now receive `-oBatchMode=yes` immediately after the command word, so a later inherited `BatchMode=no` cannot re-enable terminal prompting; unsupported prefixes and wrappers fall back to the safe non-interactive command.
- Test fix: the Git-status freshness fixture now installs its command gate before manager construction and passes an explicit environment snapshot, so tracker commands use the same gate variables as the test without relying on ambient environment reads.
@@ -0,0 +1,95 @@
---
id: "02-detach-comparison-target-materialization"
title: "Detach comparison-target materialization"
status: done
wave: 2
depends_on: ["01-propagate-instance-git-environment"]
plan: "plan.md"
spec: "../../specs/platform/requirements/workspace-git-status.md"
---
# Task 02: Detach comparison-target materialization
Move comparison-target network work out of instance readiness and Git-status request paths. Preserve fail-closed comparison state during background work.
## Red tests first
Use a controllable Git shim and synchronization channels. Add focused tests that prove these behaviors:
- initial target preparation returns while the fetch shim remains blocked
- the tracker reports `comparison_target_pending` before the fetch completes
- a successful fetch publishes ready state and starts a status refresh
- an error publishes the existing bounded unavailable code
- a newer target cannot receive a stale result from an older operation
- manager shutdown cancels an unfinished fetch
- `UpdateComparisonTargets` and `GetWorkspaceTrackerFor` do not wait for a fetch
- one HTTPS fetch error produces no SSH command and no second fetch
- instance creation returns while initial materialization remains blocked
Extend the existing browser scenario. Make the comparison remote unreadable, then prove that the session opens and file status remains usable.
Record each focused red command before production changes.
## Implementation
- Set tracker comparison state to pending before scheduling materialization.
- Schedule initial, update, rescan, submodule, and lazy materialization with the manager lifetime context.
- Bound each operation with the existing Git-command deadline.
- Track current work by repository key. Cancel or supersede old work when its target changes.
- Keep the existing identity comparison before every state publication.
- Publish ready or unavailable state only for the current target.
- Start the existing detached status refresh after state publication.
- Make manager stop wait for or cancel background target operations without leaking a goroutine.
- Remove synchronous target work from instance creation and lazy tracker creation.
- Do not add transport fallback or mutate any Git remote after an authentication error.
## Acceptance
- Kandev instance creation does not wait for comparison-target network work.
- Git-status requests do not wait for comparison-target network work.
- Comparison data remains fail-closed until the exact target is ready.
- Missing credentials produce no terminal prompt and no SSH retry.
- Shutdown leaves no target-materialization goroutine or subprocess alive.
## Likely files
- `apps/backend/internal/agentctl/server/process/manager.go`
- `apps/backend/internal/agentctl/server/process/manager_comparison_targets.go`
- `apps/backend/internal/agentctl/server/process/comparison_target_test.go`
- `apps/backend/internal/agentctl/server/process/manager_comparison_targets_test.go` (new)
- `apps/backend/internal/agentctl/server/instance/manager.go`
- `apps/backend/internal/agentctl/server/instance/manager_comparison_targets_test.go` (new)
- `apps/web/e2e/tests/git/fork-pr-comparison-target.spec.ts`
- `apps/web/e2e/tests/git/fork-pr-comparison-target-helpers.ts`
## Verification
```bash
cd apps/backend && go test ./internal/agentctl/server/process -run 'TestComparisonTarget.*(NonBlocking|Pending|Cancellation|NoTransportFallback|Stale)' -count=1
cd apps/backend && go test ./internal/agentctl/server/instance -run 'TestCreateInstanceDoesNotWaitForComparisonTarget' -count=1
cd apps/backend && go test ./internal/agentctl/server/process ./internal/agentctl/server/instance
cd apps/web && pnpm e2e:run --host --no-build --project chromium -- e2e/tests/git/fork-pr-comparison-target.spec.ts
```
## Parallelism
`sequential`. This task depends on Task 01 and owns the comparison-target lifecycle.
## Output contract
Record the red and green commands. Record startup timing proof, cancellation proof, final state transitions, and proof that no transport fallback occurs.
## Implementation record
- Red: the blocking-shim preparation test took about 400 ms while Git was blocked, proving the previous synchronous path consumed the fetch deadline before production changes.
- Green: `cd apps/backend && go test ./internal/agentctl/server/process -run 'TestComparisonTarget.*(NonBlocking|Pending|Cancellation|NoTransportFallback|Stale)' -count=1` passed 4 tests; the instance readiness regression passed 1 test; the process and instance packages passed 787 tests together.
- Startup proof: `TestCreateInstanceDoesNotWaitForComparisonTarget`, `TestComparisonTargetPreparationNonBlocking`, `TestUpdateComparisonTargetsDoesNotWaitForMaterialization`, and `TestGetWorkspaceTrackerForDoesNotWaitForMaterialization` return before the controllable Git work completes and observe pending state.
- Lifecycle proof: ready and bounded unavailable states publish only for the current target; stale operations are superseded; manager teardown cancels and drains an unfinished materialization.
- Transport proof: `TestComparisonTargetMaterializationPublishesBoundedFetchFailureNoTransportFallback` observes one HTTPS fetch attempt, no SSH command, and no second fetch. The existing fork pull-request browser scenario passed both its ready and unavailable cases.
## PR fixup record
- Review fix: comparison-target admission is closed under the same mutex as `WaitGroup.Add` during teardown, normal `Stop` reopens it only after draining, and teardown remains permanently closed.
- Review fix: the `StatusStopped` cleanup path now continues through adapter, shell, and process teardown when comparison-target shutdown returns an error.
- Test portability: lifecycle coverage uses a copied test executable as the Git shim, so state, cancellation, stale-result, and startup assertions also compile on Windows.
- Test determinism: preparation, target updates, and lazy tracker creation now use completion channels plus a closed fetch gate instead of wall-clock performance thresholds.
@@ -2,7 +2,7 @@
status: active
system: platform
created: 2026-07-19
updated: 2026-08-30
updated: 2026-08-31
owners:
- kandev
---
@@ -40,6 +40,9 @@ Users opening or focusing Changes and Review need a current workspace snapshot w
- **AC-PLATFORM-WORKSPACE-GIT-STATUS-001.13:** An untracked path inside a dependency tree does not appear in a workspace snapshot and does not receive per-file status or diff enrichment, even when the repository has no matching ignore rule.
- **AC-PLATFORM-WORKSPACE-GIT-STATUS-001.14:** A tracked changed path inside `node_modules` remains visible. An untracked path outside dependency trees remains visible when Git does not ignore it.
- **AC-PLATFORM-WORKSPACE-GIT-STATUS-001.15:** Creating, changing, or removing only untracked dependency-tree content does not change the workspace monitor fingerprint or start a full status refresh.
- **AC-PLATFORM-WORKSPACE-GIT-STATUS-001.16:** Kandev-owned comparison-target Git commands do not request credentials or confirmation through a terminal. Each command uses the instance's effective Git credential environment, enforces non-interactive prompt controls, and ends within its command deadline.
- **AC-PLATFORM-WORKSPACE-GIT-STATUS-001.17:** Comparison-target materialization does not delay instance readiness or a Git-status UI request. Until background materialization succeeds, file status remains usable and comparison-derived data reports unavailable.
- **AC-PLATFORM-WORKSPACE-GIT-STATUS-001.18:** When a comparison-target fetch fails over its canonical HTTPS transport, Kandev does not retry SSH or another transport automatically. It preserves checkout and push routing and reports that comparison data is unavailable.
## Out of scope
@@ -47,6 +50,7 @@ Users opening or focusing Changes and Review need a current workspace snapshot w
- Suppressing tracked paths based on a directory name.
- Filtering dependency trees only after Git has enumerated their files.
- Changing the Git-status API or WebSocket payload shape.
- Automatically changing the Git transport after an authentication or transport error.
## System design
@@ -4,7 +4,7 @@ system: platform
requirements:
- REQ-PLATFORM-WORKSPACE-GIT-STATUS-001
created: 2026-07-19
updated: 2026-08-30
updated: 2026-08-31
owners:
- kandev
---
@@ -18,7 +18,7 @@ This design preserves the technical source detail for `REQ-PLATFORM-WORKSPACE-GI
| Requirement | Design section |
| --- | --- |
| `REQ-PLATFORM-WORKSPACE-GIT-STATUS-001` | [Migrated source detail](#migrated-source-detail), [Generated untracked dependency trees](#generated-untracked-dependency-trees), [Mixed index and working-tree changes](#mixed-index-and-working-tree-changes), [API surface](#api-surface) |
| `REQ-PLATFORM-WORKSPACE-GIT-STATUS-001` | [Migrated source detail](#migrated-source-detail), [Generated untracked dependency trees](#generated-untracked-dependency-trees), [Mixed index and working-tree changes](#mixed-index-and-working-tree-changes), [Comparison-target Git execution](#comparison-target-git-execution), [API surface](#api-surface) |
## Migrated source detail
@@ -120,6 +120,26 @@ A branch name alone is not a complete comparison identity. A task may be attache
- Kandev does not broaden task Git credentials to materialize a target. Public targets and targets already readable through the execution's effective Git credentials are supported. An unreadable private target fails visibly.
- Target setup is fail-closed. If identity validation, remote collision checks, fetch, or merge-base resolution fails, file status remains usable, but comparison-derived totals, ahead/behind, commits, and cumulative diff are unavailable. The Changes panel names the intended `<owner>/<repository>:<branch>` target and shows an actionable comparison error; task-list summaries suppress numeric Git totals and expose the unavailable state instead of publishing a same-named `origin` fallback.
### Comparison-target Git execution
The instance's effective Git environment is authoritative for Kandev-owned workspace Git commands. This environment contains executor credentials and managed credential-helper entries. The process manager gives a detached environment copy to each workspace tracker. This rule applies to root, repository, submodule, rescan, and lazy trackers.
Each tracker starts Git with its instance environment, not the ambient environment of agentctl. The command environment preserves managed `GIT_CONFIG_*` entries and the command and options from a direct OpenSSH command, while placing `BatchMode=yes` before inherited batch-mode options. Unsupported shell prefixes or wrappers use the safe non-interactive default. It also enforces the established non-interactive controls:
- `GIT_TERMINAL_PROMPT=0`
- `GCM_INTERACTIVE=Never`
- `GIT_ASKPASS=echo`
- `SSH_ASKPASS=/bin/false`
- `GIT_SSH_COMMAND=ssh -oBatchMode=yes` when the instance does not supply an SSH command
These values prevent Git, Git Credential Manager, and SSH from reading the launcher terminal. Each command keeps the existing Git-command deadline and throttle behavior.
The process manager sets an explicit target to `pending` before it starts network work. It then materializes the target with the manager's lifetime context. Initial materialization, live updates, rescan, and lazy tracker creation do not wait for the fetch. A successful fetch publishes the exact comparison ref and starts a detached status refresh. An error publishes a bounded unavailable state. Manager shutdown cancels unfinished materialization.
Kandev selects the transport before it starts a comparison-target command. Canonical comparison targets remain HTTPS. An HTTPS authentication or transport error does not start an SSH retry. This rule prevents a command from changing identity, host trust, or credential scope after the first error. Kandev does not rewrite `origin`, the checkout upstream, or push routing.
This contract follows [ADR-2026-08-31-deterministic-noninteractive-git-transport](../../../decisions/2026-08-31-deterministic-noninteractive-git-transport.md).
## API surface
Existing Git-status routes remain in place. Their result and stream payloads add optional comparison state so old clients continue to decode them:
@@ -155,6 +175,9 @@ Existing Git-status routes remain in place. Their result and stream payloads add
| The PR head repository or branch does not match exactly one task attachment | The PR remains associated for Review, but no attachment comparison target changes; the mismatch is logged with task, repository, and branch identity. |
| The configured comparison remote already exists with another URL | Target setup fails closed and reports `comparison_remote_conflict`; Kandev does not overwrite the remote or fall back to `origin`. |
| The configured target branch cannot be fetched | File status remains available; comparison-derived data is unavailable with `comparison_fetch_failed`. Prior or same-named origin statistics are not published as current. |
| The target needs credentials that are not in the instance environment | Git does not read the launcher terminal. The command ends within its deadline and comparison data reports unavailable. |
| A comparison-target fetch is slow or unreachable | Instance readiness and Git-status UI requests continue. The target remains pending or unavailable until the background command ends. |
| An HTTPS comparison-target fetch fails | Kandev does not retry SSH. The selected remotes, upstream, credential scope, and push route remain unchanged. |
| The backend or executor restarts | The persisted target is revalidated and materialized before comparison-derived status becomes authoritative. |
## Scenarios
@@ -184,6 +207,9 @@ Existing Git-status routes remain in place. Their result and stream payloads add
- **GIVEN** a historical PR for a previous checkout branch, **WHEN** provider sync refreshes it, **THEN** it cannot replace the current branch's comparison target.
- **GIVEN** a live cross-fork target, **WHEN** the backend restarts and the session resumes, **THEN** Kandev reconstructs the same comparison remote/ref before publishing authoritative totals.
- **GIVEN** an explicit target that cannot be fetched, **WHEN** Changes and task-list surfaces refresh, **THEN** working-tree files stay visible, comparison-derived values are marked unavailable, and no inflated same-named-origin total is shown.
- **GIVEN** an HTTPS comparison target that requires missing credentials, **WHEN** Kandev starts an instance, **THEN** the launcher terminal receives no prompt and instance readiness does not wait for the fetch.
- **GIVEN** the same missing HTTPS credentials, **WHEN** target materialization fails, **THEN** Kandev reports comparison data unavailable and does not try an SSH URL.
- **GIVEN** a slow comparison-target fetch, **WHEN** a lazy repository tracker is requested, **THEN** the tracker returns immediately with pending comparison state and file status remains usable.
- **GIVEN** a provider-derived target, **WHEN** the user selects a branch from the attachment's **Compare against** picker, **THEN** the provider target is removed atomically and the selected local-repository branch becomes authoritative.
## Out of scope
@@ -203,7 +229,8 @@ Existing Git-status routes remain in place. Their result and stream payloads add
- Defining new behavior for Git's unmerged/conflict porcelain states; those continue to follow their existing handling.
- Suppressing untracked `.next`, `dist`, `build`, or other generated directories without a Git ignore rule.
- Adding client-side dependency-tree filtering or changing status payload fields.
- Retrying an HTTPS comparison target through SSH or another transport.
## Implementation plan
See [Workspace Git Status Scalability plan](../../../plans/workspace-git-status-scalability/plan.md), [Workspace Git Status Dependency-Tree Exclusion plan](../../../plans/workspace-git-status-dependency-tree-exclusion/plan.md), [Fork PR Comparison Targets plan](../../../plans/fork-pr-comparison-targets/plan.md), and [Mixed Staged and Unstaged Changes plan](../../../plans/mixed-staged-unstaged-changes/plan.md).
See [Workspace Git Status Scalability plan](../../../plans/workspace-git-status-scalability/plan.md), [Workspace Git Status Dependency-Tree Exclusion plan](../../../plans/workspace-git-status-dependency-tree-exclusion/plan.md), [Fork PR Comparison Targets plan](../../../plans/fork-pr-comparison-targets/plan.md), [Non-interactive Comparison-target Git plan](../../../plans/noninteractive-comparison-target-git/plan.md), and [Mixed Staged and Unstaged Changes plan](../../../plans/mixed-staged-unstaged-changes/plan.md).