diff --git a/CLAUDE.md b/CLAUDE.md index 46c7760..d0d837b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,6 +105,8 @@ Optional daemon services (feature-gated via config): - **CodexUsageSyncService**: Syncs Codex usage to `/api/v1/codex-usage` every 10 min, only while a `codex`/`chatgpt` process is running (both intervals share the `usageSyncInterval` const in `daemon/usage_sync.go`) - **SyncCircuitBreakerService**: Retry failed syncs with file-based persistence (`~/.shelltime/sync-pending.jsonl`, one sync message per line, of any length) and hourly recovery timer. `SaveForRetry` and the timer's read-republish-rewrite share a lock, and the rewrite keeps lines saved while it was republishing - **AICodeOtelServer**: gRPC OTEL collector for AI coding CLI metrics, logs and traces (Claude Code, Codex). Spans (`claude_code.interaction`, `llm_request`, `tool`, ...) go to the same `/api/v1/cc/otel` endpoint in `spans`; a span without `session.id` takes it from another span of its trace in the same export. `shelltime cc install` turns traces on (`CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`, `OTEL_TRACES_EXPORTER=otlp`). In a Claude Code cloud session (`CLAUDE_CODE_REMOTE=true`, where the SessionStart hook starts the daemon) it adds the VM's `CLAUDE_CODE_REMOTE_SESSION_ID` as the `ccr.session.id` attribute to Claude Code records that lack it; the server marks those sessions as cloud sessions. `daemon/main_test.go` clears both variables so tests behave the same inside a cloud session +- **Git repositories** (`model/git_repository.go`): the server groups coding agent sessions into projects by git repository, not folder, so a renamed or moved clone, a worktree or a subfolder stays one project. `GitRepositoryResolver` asks the git CLI (found through `CommandService`, so the daemon's limited PATH reaches Homebrew) for a directory's top level and its `origin` remote (else `upstream`, else the first by name; `remote get-url`, so `insteadOf` applies) without optional locks, within one 2 s budget per lookup, since the daemon resolves on the OTLP export path. Concurrent lookups of one directory share one run, which goes on its own goroutine: a stat or git blocked in the kernel (a hung network mount) ignores the context, so the lookup is given up on after the budget (plus `gitRepositoryGrace`), or when its caller's context ends, and the directory gets no other until it returns (its answer is kept then). git runs with `LC_ALL=C`, since its messages are read; a remote's path segments are decoded and escaped again (`url.PathEscape`), like the server's. A migration run stops asking after `projectMigrationMaxUnanswered` folders' stats timed out (a hung mount; git refusing a folder doesn't count), and a folder that doesn't exist counts as missing, one it can't stat otherwise as unchecked. git refusing a repository it doesn't trust (`safe.directory`) or killed by a signal is no answer about the directory; a git binary not found is looked for again every 30 s. It keeps definitive answers, negative ones too (10 min in the daemon), and a timeout or git failing to start for 30 s only, reported as unknown by `Lookup` (`Resolve` drops the flag). `CanonicalRepositoryURL` turns any remote into `https:///` without credentials, port or `.git`, the form Claude Code reports; a local path is no repository. The repository travels as `vcs.repository.url.full` (`model.AICodeRepositoryAttribute`): the OTEL processor adds it to metrics and log events whose resource has a `pwd` and that don't name one (not to spans: the server keys a session from its events), and never when the resource names one (Claude Code's own value wins; git isn't asked then), the socket's `session_project` handler sends it with the statusline's directory, and backfill adds it to uploaded events (Codex's `session_meta.git.repository_url` first, since it was true when the session ran, else the transcript directory's). `aiCodeOtel.sendRepository: false` (`ShellTimeConfig.SendsRepository`) turns all of it off: no resolver in the processor or the socket, the processor removes the attribute from every record (the agent's own too), backfill attaches none, and neither the daemon nor `cc projects` migrates +- **Project migration** (`daemon/project_migration.go`, `model/project_migration.go`): sessions recorded before the repository was sent are folder projects on the server. A while after start the daemon runs `MigrateProjectRepositories` once, never in AI cloud only mode (marker `~/.shelltime/project-repositories.v1`, written only when the run is `Complete`: a 404 from an older server, a failure, more pages than one run goes through (50), a folder git couldn't answer for, or a machine without a host name of its own leaves none, so the next start tries again): it lists the folder projects of this machine's names (`ProjectMigrationHosts`: the host name, without its domain, and the `machine.name` in `~/.claude/settings.json`, leaving out names many machines share, like `localhost`, `genericHostNames`) from `POST /api/v1/cc/projects/unresolved`, a page at a time by the last project of the page (`after`), and posts the folders that still exist and are clones to `POST /api/v1/cc/projects/repositories`. `shelltime cc projects` / `shelltime codex projects` run it by hand (`--dry-run` lists what would move; skipped in AI cloud only mode) - **HeartbeatResyncService**: Periodic resync of failed heartbeats (30-min interval) - **CleanupTimerService**: Periodic log file cleanup (24-hour interval) diff --git a/README.md b/README.md index 62667e4..a398a40 100644 --- a/README.md +++ b/README.md @@ -101,9 +101,11 @@ shelltime codex install | `shelltime cc statusline` | Print the Claude Code statusline (reads the session JSON Claude Code sends on stdin) | | `shelltime cc backfill` | Upload past Claude Code usage from local transcripts | | `shelltime cc pr --session-id ...` | Link pull requests to a Claude Code session (called by the ShellTime Claude Code mod) | +| `shelltime cc projects` | Group this machine's coding agent projects by git repository instead of folder (`--dry-run` lists what would move). The daemon does this once on its own; see [Projects](#projects) | | `shelltime codex install` | Add ShellTime OTEL config to `~/.codex/config.toml` | | `shelltime codex uninstall` | Remove ShellTime OTEL config from `~/.codex/config.toml` | | `shelltime codex backfill` | Upload past Codex usage from local session files | +| `shelltime codex projects` | Same as `shelltime cc projects`: the projects of both agents are grouped together | ### Environment helpers @@ -199,6 +201,14 @@ For formatting details and platform notes, see [docs/CC_STATUSLINE.md](docs/CC_S Besides tokens and cost, both tools then send your prompts, tool details (shell commands, file paths, truncated tool input or output, errors) and the assistant's responses. To keep some of these out, set `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS` or `OTEL_LOG_ASSISTANT_RESPONSES` to `0` in the `env` of `~/.claude/settings.json`, or `otel.log_user_prompt` / `otel.log_agent_responses` to `false` in `~/.codex/config.toml`. Re-running the install command resets them. `shelltime doctor` warns when a config written by an older version is missing newer keys, and `shelltime doctor --fix` re-runs the install. +## Projects + +ShellTime groups your coding agent sessions into projects by the git repository they ran in, so a renamed or moved clone, a worktree or a subfolder stays one project. The repository comes from the folder's `origin` remote (else `upstream`, else the first remote), sent as `https:///` with any credentials in the remote URL removed. Claude Code reports it itself (`shelltime cc install` turns this on); for Codex and older Claude Code setups the daemon asks git about the session's folder. Sessions outside a repository, or in one without a remote, are grouped by machine and folder. + +Sessions recorded before this were grouped by folder. A couple of minutes after it starts, the daemon moves this machine's folder projects whose folders still exist and are clones into their repository's project, once, and leaves `~/.shelltime/project-repositories.v1` behind. `shelltime cc projects` does the same by hand (`--dry-run` shows the folders and repositories without changing anything). Folders that no longer exist (renamed or deleted) can't be checked, and neither can a folder on a drive that isn't mounted, so run `shelltime cc projects` again once it is, and host names many machines share, like `localhost`, are skipped. A folder moves whole, into the repository it is a clone of today, so only folders where no session ever named a repository are moved this way: the server keys the others from the sessions that did, each session from the closest one before it. + +To keep repository names to yourself, set `sendRepository: false` under `aiCodeOtel` in `~/.shelltime/config.yaml`. The daemon then never asks git, removes the repository Claude Code reports, and skips the migration; sessions are grouped by machine and folder. Restart the daemon (`shelltime daemon reinstall`) for a change to take effect. + ## Codex Usage Tracking ShellTime receives Codex data through two independent paths: diff --git a/cmd/daemon/main.go b/cmd/daemon/main.go index cf7f34e..1d748b2 100644 --- a/cmd/daemon/main.go +++ b/cmd/daemon/main.go @@ -199,6 +199,12 @@ func main() { // (statusline mods, the desktop app, idle sessions). processor.StartAnthropicUsageSync() + // Group the sessions recorded before repositories were named by repository, not folder. + // A cloud VM is no machine of the user's, and its home doesn't outlive the session. + if !aiCloudOnly { + go daemon.RunProjectMigrationOnce(ctx, cfg) + } + // Handle shutdown gracefully sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) diff --git a/commands/aicode_backfill.go b/commands/aicode_backfill.go index 7a38d29..1f93041 100644 --- a/commands/aicode_backfill.go +++ b/commands/aicode_backfill.go @@ -150,6 +150,11 @@ func runAICodeBackfill(c *cli.Context, src aiCodeBackfillSource) error { return nil } + // The server groups sessions into projects by git repository when it knows it. + if cfg.SendsRepository() { + model.AttachBackfillRepositories(ctx, plan.upload, model.NewGitRepositoryResolver(time.Hour)) + } + batches := model.PackBackfillBatches(src.clientType, plan.upload, model.AICodeBackfillMaxEvents, model.AICodeBackfillMaxBatchBytes, model.AICodeBackfillMaxCompleted) accepted := 0 diff --git a/commands/aicode_projects.go b/commands/aicode_projects.go new file mode 100644 index 0000000..9088ff7 --- /dev/null +++ b/commands/aicode_projects.go @@ -0,0 +1,107 @@ +package commands + +import ( + "errors" + "fmt" + "net/http" + "os" + "strconv" + "time" + + "github.com/gookit/color" + "github.com/malamtime/cli/model" + "github.com/olekukonko/tablewriter" + "github.com/urfave/cli/v2" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/trace" +) + +// AICodeProjectsCommand is `shelltime cc projects` and `shelltime codex projects`: the projects +// of both agents are grouped together, so either runs the same migration. +var AICodeProjectsCommand = &cli.Command{ + Name: "projects", + Usage: "Group this machine's coding agent projects by git repository instead of folder", + Description: "Sessions recorded before ShellTime named their git repository are grouped into projects by\n" + + "machine and folder, so a renamed or moved clone shows up as another project. This finds the\n" + + "repository of each such folder that still exists on this machine and moves its sessions into\n" + + "that repository's project. The daemon does this once on its own; run it again any time.", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "dry-run", + Usage: "show which folders would move without changing anything", + }, + }, + Action: commandAICodeProjects, +} + +// aiCodeProjectsHosts names this machine for the migration; tests replace it. +var aiCodeProjectsHosts = func() []string { + return model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) +} + +func commandAICodeProjects(c *cli.Context) error { + ctx, span := commandTracer.Start(c.Context, "aicode.projects", trace.WithSpanKind(trace.SpanKindClient)) + defer span.End() + SetupLogger(os.ExpandEnv("$HOME/" + model.COMMAND_BASE_STORAGE_FOLDER)) + + cfg, err := configService.ReadConfigFile(ctx) + if err != nil { + return err + } + if cfg.Token == "" { + return errors.New("no ShellTime token configured, run `shelltime init` first") + } + if skippedInAICloudOnly(cfg, "Projects not grouped") { + return nil + } + if !cfg.SendsRepository() { + color.Yellow.Println("Projects not grouped: aiCodeOtel.sendRepository is off, so no repository is sent.") + return nil + } + endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint} + hosts := aiCodeProjectsHosts() + if len(hosts) == 0 { + return errors.New("this machine's host name is one many machines share (like localhost), so its projects can't be told apart from theirs") + } + dryRun := c.Bool("dry-run") + + color.Yellow.Println("Looking for projects grouped by folder...") + result, err := model.MigrateProjectRepositories(ctx, endpoint, hosts, model.NewGitRepositoryResolver(time.Hour), dryRun) + span.SetAttributes(attribute.Int("checked", result.Checked), attribute.Int("linked", len(result.Linked))) + if err != nil { + var statusErr *model.HTTPStatusError + if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusNotFound { + return errors.New("the ShellTime server can't group projects by repository yet, please try again after it is updated") + } + return fmt.Errorf("project migration failed: %w", err) + } + + if result.Checked == 0 { + color.Green.Println("Every project of this machine is already grouped by repository.") + return nil + } + if len(result.Linked) > 0 { + w := tablewriter.NewWriter(os.Stdout) + w.Header([]string{"FOLDER", "REPOSITORY"}) + for _, p := range result.Linked { + w.Append([]string{p.Pwd, p.Repository}) + } + w.Render() + } + + fmt.Printf("%d folder projects found: %d in a git repository, %d no longer here, %d not in a repository with a remote.\n", + result.Checked, len(result.Linked), result.Missing, result.NotRepositories) + if result.Unchecked > 0 { + color.Yellow.Printf("git didn't answer for %d folders; run it again to check them.\n", result.Unchecked) + } + if result.Truncated { + color.Yellow.Println("This machine has more folder projects than one run goes through; run it again to check the rest.") + } + switch { + case dryRun: + color.Green.Println("Dry run: nothing was changed.") + case len(result.Linked) > 0: + color.Green.Printf("Moved %s sessions into their repositories' projects.\n", strconv.Itoa(result.Sessions)) + } + return nil +} diff --git a/commands/aicode_projects_test.go b/commands/aicode_projects_test.go new file mode 100644 index 0000000..8f6afb7 --- /dev/null +++ b/commands/aicode_projects_test.go @@ -0,0 +1,83 @@ +package commands + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os/exec" + "testing" + + "github.com/malamtime/cli/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "github.com/urfave/cli/v2" +) + +func runProjects(t *testing.T, group string, token, endpoint string, args ...string) error { + t.Helper() + setupCCTest(t) + original := configService + mc := model.NewMockConfigService(t) + mc.On("ReadConfigFile", mock.Anything).Return(model.ShellTimeConfig{Token: token, APIEndpoint: endpoint}, nil).Maybe() + configService = mc + t.Cleanup(func() { configService = original }) + + // The machine's own host name may be a generic one (a CI runner's), which names nothing. + originalHosts := aiCodeProjectsHosts + aiCodeProjectsHosts = func() []string { return []string{"mbp"} } + t.Cleanup(func() { aiCodeProjectsHosts = originalHosts }) + + app := &cli.App{Name: "t", Commands: []*cli.Command{{Name: group, Subcommands: []*cli.Command{AICodeProjectsCommand}}}} + return app.Run(append([]string{"t", group, "projects"}, args...)) +} + +func TestAICodeProjectsMovesClones(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + dir := t.TempDir() + for _, args := range [][]string{{"init", "-q"}, {"remote", "add", "origin", "https://github.com/acme/web.git"}} { + out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput() + require.NoError(t, err, string(out)) + } + + var moves int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/v1/cc/projects/unresolved": + _ = json.NewEncoder(w).Encode(map[string]any{"projects": []map[string]any{{"host": "mbp", "pwd": dir, "sessions": 2}}}) + case "/api/v1/cc/projects/repositories": + moves++ + _ = json.NewEncoder(w).Encode(map[string]int{"updated": 2}) + } + })) + t.Cleanup(server.Close) + + require.NoError(t, runProjects(t, "codex", "tok", server.URL, "--dry-run")) + assert.Zero(t, moves) + require.NoError(t, runProjects(t, "cc", "tok", server.URL)) + assert.Equal(t, 1, moves) +} + +func TestAICodeProjectsSkippedInAICloudOnly(t *testing.T) { + t.Setenv("CLAUDE_CODE_REMOTE", "true") + var requests int + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + })) + t.Cleanup(server.Close) + + require.NoError(t, runProjects(t, "cc", "tok", server.URL)) + assert.Zero(t, requests, "a cloud VM sends no host name or folders") +} + +func TestAICodeProjectsErrors(t *testing.T) { + assert.ErrorContains(t, runProjects(t, "cc", "", "http://127.0.0.1:0"), "no ShellTime token") + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + t.Cleanup(server.Close) + assert.ErrorContains(t, runProjects(t, "cc", "tok", server.URL), "can't group projects by repository yet") +} diff --git a/commands/cc.go b/commands/cc.go index 79a5443..282dfc4 100644 --- a/commands/cc.go +++ b/commands/cc.go @@ -15,6 +15,7 @@ var CCCommand = &cli.Command{ CCStatuslineCommand, CCBackfillCommand, CCPullRequestCommand, + AICodeProjectsCommand, }, } diff --git a/commands/codex.go b/commands/codex.go index 312fa5b..118604f 100644 --- a/commands/codex.go +++ b/commands/codex.go @@ -13,6 +13,7 @@ var CodexCommand = &cli.Command{ CodexInstallCommand, CodexUninstallCommand, CodexBackfillCommand, + AICodeProjectsCommand, }, } diff --git a/daemon/aicode_otel_processor.go b/daemon/aicode_otel_processor.go index 7547c1d..3bc94d4 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -40,6 +40,12 @@ type AICodeOtelProcessor struct { // cloudSessionID is the Claude Code cloud session the daemon runs in (from its environment), // added to Claude Code records that don't carry one. Empty on a local machine. cloudSessionID string + // repos finds the git repository of a record's working directory, so the server can group + // sessions by repository rather than by folder. Nil adds no repository. + repos *model.GitRepositoryResolver + // dropRepository removes vcs.repository.url.full from every record, the agent's own too + // (aiCodeOtel.sendRepository: false). + dropRepository bool // maxRequestBytes bounds the JSON body of one backend request; larger batches are split. maxRequestBytes int @@ -55,6 +61,10 @@ func NewAICodeOtelProcessor(config model.ShellTimeConfig) *AICodeOtelProcessor { } debug := config.AICodeOtel != nil && config.AICodeOtel.Debug != nil && *config.AICodeOtel.Debug + var repos *model.GitRepositoryResolver + if config.SendsRepository() { + repos = model.NewGitRepositoryResolver(repositoryCacheTTL) + } return &AICodeOtelProcessor{ config: config, @@ -65,10 +75,78 @@ func NewAICodeOtelProcessor(config model.ShellTimeConfig) *AICodeOtelProcessor { hostname: hostname, debug: debug, cloudSessionID: model.CloudSessionIDFromEnv(os.Getenv), + repos: repos, + dropRepository: !config.SendsRepository(), maxRequestBytes: model.AICodeOtelMaxRequestBytes, } } +// repositoryCacheTTL is how long the daemon trusts what git said about a directory. A remote +// rarely changes; a folder that becomes a clone is picked up within this time. +const repositoryCacheTTL = 10 * time.Minute + +// resolveRepository returns the canonical URL of the repository the resource's working +// directory belongs to, or "". A resource that names its repository itself needs no lookup. +func (p *AICodeOtelProcessor) resolveRepository(ctx context.Context, res *otelResource) string { + if p.repos == nil || res.attrs.Pwd == "" { + return "" + } + if _, ok := res.attrs.Attributes[model.AICodeRepositoryAttribute]; ok { + return "" + } + repo := p.repos.Resolve(ctx, res.attrs.Pwd) + res.repositoryRoot = repo.Root + return repo.URL +} + +// insideDir reports whether path is root or a directory below it. +func insideDir(path, root string) bool { + if root == "" { + return false + } + rel, err := filepath.Rel(root, filepath.Clean(path)) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) +} + +// fillRepository adds the repository of the resource's working directory to a record that +// doesn't name one. It is seeded before the record's own attributes, so a +// vcs.repository.url.full that Claude Code sent on the record still wins, and it adds nothing +// when the agent named the repository on the resource (events carry that one already; metrics +// don't copy the resource's other attributes, and must not get a different one from the folder). +func fillRepository(attrs map[string]any, res *otelResource) map[string]any { + if res.repository == "" { + return attrs + } + if _, ok := attrs[model.AICodeRepositoryAttribute]; ok { + return attrs + } + if _, ok := res.attrs.Attributes[model.AICodeRepositoryAttribute]; ok { + return attrs + } + return setAttribute(attrs, model.AICodeRepositoryAttribute, res.repository) +} + +// unfillRepository takes back the repository fillRepository added when the record named a +// working directory of its own outside the resource's work tree: the repository is the +// resource's folder's, not necessarily that one's. A subfolder of the same work tree keeps it, +// and so does a repository the record itself named. +func unfillRepository(attrs map[string]any, res *otelResource, filled bool, pwd string) { + if !filled || pwd == "" || pwd == res.attrs.Pwd || insideDir(pwd, res.repositoryRoot) { + return + } + delete(attrs, model.AICodeRepositoryAttribute) +} + +// namesRepository reports whether a record's own attributes name its repository. +func namesRepository(attrs []*commonv1.KeyValue) bool { + for _, attr := range attrs { + if attr.GetKey() == model.AICodeRepositoryAttribute { + return true + } + } + return false +} + // fillCloudSessionID adds the daemon's cloud session id to the attributes of a Claude Code // record that doesn't carry ccr.session.id yet. In a cloud VM the daemon is started by the // session's SessionStart hook, so every Claude Code record it receives belongs to that session. @@ -117,6 +195,11 @@ type otelResource struct { attrs *model.AICodeOtelResourceAttributes // digest identifies the resource in stable ids. It is computed once per resource. digest [sha256.Size]byte + // repository is the canonical URL of the git repository of the resource's working + // directory, or "" (see resolveRepository). + repository string + // repositoryRoot is the top level of that repository's work tree. + repositoryRoot string } // deterministicMarshal encodes OTLP messages byte-for-byte reproducibly, so an exporter retry of @@ -185,6 +268,7 @@ func (p *AICodeOtelProcessor) ProcessMetrics(ctx context.Context, req *collmetri // Extract resource attributes once for all metrics in this resource res := newOtelResource(resource, source) + res.repository = p.resolveRepository(ctx, res) project := p.detectProject(resource, source) var metrics []model.AICodeOtelMetric @@ -231,6 +315,7 @@ func (p *AICodeOtelProcessor) ProcessLogs(ctx context.Context, req *collogsv1.Ex // Extract resource attributes once for all events in this resource res := newOtelResource(resource, source) + res.repository = p.resolveRepository(ctx, res) project := p.detectProject(resource, source) var events []model.AICodeOtelEvent @@ -281,6 +366,9 @@ func (p *AICodeOtelProcessor) ProcessTraces(ctx context.Context, req *colltracev for _, ss := range rs.GetScopeSpans() { for _, s := range ss.GetSpans() { if span := parseSpan(s, source, attrs); span != nil { + if p.dropRepository { + dropSpanRepository(span) + } spans = append(spans, *span) } } @@ -378,6 +466,15 @@ func parseSpan(s *tracev1.Span, source string, res *model.AICodeOtelResourceAttr return span } +// dropSpanRepository removes the repository from a span and its events +// (aiCodeOtel.sendRepository: false). +func dropSpanRepository(span *model.AICodeOtelSpan) { + delete(span.Attributes, model.AICodeRepositoryAttribute) + for i := range span.Events { + delete(span.Events[i].Attributes, model.AICodeRepositoryAttribute) + } +} + // fillSpanSessionIDs gives spans without a session id the one another span of the same trace // carries. func fillSpanSessionIDs(spans []model.AICodeOtelSpan) { @@ -671,10 +768,17 @@ func (p *AICodeOtelProcessor) parseMetric(m *metricsv1.Metric, res *otelResource // Seeded before the data point's attributes, so they can't crowd it out; a ccr.session.id // on the data point still wins. metric.Attributes = p.fillCloudSessionID(metric.Attributes, res.source) + _, had := metric.Attributes[model.AICodeRepositoryAttribute] + metric.Attributes = fillRepository(metric.Attributes, res) + _, has := metric.Attributes[model.AICodeRepositoryAttribute] // Then extract data point attributes (can override resource attrs) for _, attr := range dp.GetAttributes() { applyMetricAttribute(&metric, attr, metricType) } + unfillRepository(metric.Attributes, res, has && !had && !namesRepository(dp.GetAttributes()), metric.Pwd) + if p.dropRepository { + delete(metric.Attributes, model.AICodeRepositoryAttribute) + } metrics = append(metrics, metric) } @@ -761,16 +865,23 @@ func (p *AICodeOtelProcessor) parseLogRecord(lr *logsv1.LogRecord, res *otelReso } // Seeded the same way: a ccr.session.id on the record itself still wins. event.Attributes = p.fillCloudSessionID(event.Attributes, res.source) + _, had := event.Attributes[model.AICodeRepositoryAttribute] + event.Attributes = fillRepository(event.Attributes, res) + _, has := event.Attributes[model.AICodeRepositoryAttribute] var fallbacks eventFallbacks for _, attr := range lr.GetAttributes() { applyEventAttribute(event, &fallbacks, attr.GetKey(), attr.GetValue()) } fallbacks.apply(event, res.attrs) + unfillRepository(event.Attributes, res, has && !had && !namesRepository(lr.GetAttributes()), event.Pwd) if event.SessionID == "" && event.ConversationID != "" { event.SessionID = event.ConversationID } + if p.dropRepository { + delete(event.Attributes, model.AICodeRepositoryAttribute) + } return event } diff --git a/daemon/aicode_otel_repository_test.go b/daemon/aicode_otel_repository_test.go new file mode 100644 index 0000000..793639b --- /dev/null +++ b/daemon/aicode_otel_repository_test.go @@ -0,0 +1,152 @@ +package daemon + +import ( + "context" + "os/exec" + "path/filepath" + "testing" + + "github.com/malamtime/cli/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + metricsv1 "go.opentelemetry.io/proto/otlp/metrics/v1" +) + +// gitRepoWithOrigin creates a work tree whose origin is remote. +func gitRepoWithOrigin(t *testing.T, remote string) string { + t.Helper() + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + dir := t.TempDir() + for _, args := range [][]string{{"init", "-q"}, {"remote", "add", "origin", remote}} { + out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput() + require.NoError(t, err, string(out)) + } + return dir +} + +// A record whose working directory is a clone gets the clone's repository, so the server groups +// it by repository; a repository the record names itself wins. +func TestRepositoryFromWorkingDirectory(t *testing.T) { + dir := gitRepoWithOrigin(t, "git@github.com:acme/web.git") + p := NewAICodeOtelProcessor(model.ShellTimeConfig{}) + + codex := newOtelResource(serviceResource("codex_cli_rs", kv("pwd", strVal(dir))), model.AICodeOtelSourceCodex) + codex.repository = p.resolveRepository(context.Background(), codex) + require.Equal(t, "https://github.com/acme/web", codex.repository) + + event := p.parseLogRecord(codexRecord("user_prompt", kv("prompt", strVal("hi"))), codex, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "https://github.com/acme/web", event.Attributes[model.AICodeRepositoryAttribute]) + + event = p.parseLogRecord(codexRecord("user_prompt", kv("vcs.repository.url.full", strVal("https://github.com/acme/other"))), codex, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "https://github.com/acme/other", event.Attributes[model.AICodeRepositoryAttribute], "the record's own value wins") + + // Claude Code without OTEL_METRICS_INCLUDE_REPOSITORY, and a pwd resource attribute. + plainClaude := newOtelResource(serviceResource("claude-code", kv("pwd", strVal(dir))), model.AICodeOtelSourceClaudeCode) + plainClaude.repository = p.resolveRepository(context.Background(), plainClaude) + delta := metricsv1.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA + metrics := p.parseMetric(sumMetric("claude_code.active_time.total", delta, 30, kv("type", strVal("cli"))), plainClaude, "com.anthropic.claude_code") + require.Len(t, metrics, 1) + assert.Equal(t, "https://github.com/acme/web", metrics[0].Attributes[model.AICodeRepositoryAttribute]) + metrics = p.parseMetric(sumMetric("claude_code.active_time.total", delta, 30, kv("vcs.repository.url.full", strVal("https://github.com/acme/other"))), plainClaude, "com.anthropic.claude_code") + require.Len(t, metrics, 1) + assert.Equal(t, "https://github.com/acme/other", metrics[0].Attributes[model.AICodeRepositoryAttribute], "the data point's own value wins") + + // Claude Code names its repository on the resource; the daemon leaves it alone. + claude := newOtelResource(serviceResource("claude-code", + kv("pwd", strVal(dir)), + kv("vcs.repository.url.full", strVal("https://github.com/example-org/example-repo")), + ), model.AICodeOtelSourceClaudeCode) + claude.repository = p.resolveRepository(context.Background(), claude) + assert.Empty(t, claude.repository, "no lookup when the resource names its repository") + event = p.parseLogRecord(claudeRecord("user_prompt", kv("prompt", strVal("hi"))), claude, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "https://github.com/example-org/example-repo", event.Attributes[model.AICodeRepositoryAttribute]) + // Metrics don't copy the resource's other attributes, and get no different repository from + // the folder either, even with a repository resolved for it. + claude.repository = "https://github.com/acme/web" + metrics = p.parseMetric(sumMetric("claude_code.active_time.total", delta, 30, kv("type", strVal("cli"))), claude, "com.anthropic.claude_code") + require.Len(t, metrics, 1) + assert.NotContains(t, metrics[0].Attributes, model.AICodeRepositoryAttribute) +} + +func TestRepositoryNeedsAWorkingDirectory(t *testing.T) { + p := NewAICodeOtelProcessor(model.ShellTimeConfig{}) + for _, res := range []*otelResource{ + newOtelResource(claudeTestResource(), model.AICodeOtelSourceClaudeCode), + newOtelResource(serviceResource("codex_cli_rs", kv("pwd", strVal(t.TempDir()))), model.AICodeOtelSourceCodex), + } { + assert.Empty(t, p.resolveRepository(context.Background(), res)) + } + + p.repos = nil + dir := gitRepoWithOrigin(t, "https://github.com/acme/web") + res := newOtelResource(serviceResource("codex_cli_rs", kv("pwd", strVal(dir))), model.AICodeOtelSourceCodex) + assert.Empty(t, p.resolveRepository(context.Background(), res), "a processor without a resolver adds nothing") +} + +// With aiCodeOtel.sendRepository off, the daemon asks git nothing and removes the repository an +// agent reports itself. +func TestRepositoryNotSentWhenTurnedOff(t *testing.T) { + dir := gitRepoWithOrigin(t, "git@github.com:acme/web.git") + off := false + p := NewAICodeOtelProcessor(model.ShellTimeConfig{AICodeOtel: &model.AICodeOtel{SendRepository: &off}}) + assert.Nil(t, p.repos) + + codex := newOtelResource(serviceResource("codex_cli_rs", kv("pwd", strVal(dir))), model.AICodeOtelSourceCodex) + codex.repository = p.resolveRepository(context.Background(), codex) + assert.Empty(t, codex.repository) + event := p.parseLogRecord(codexRecord("user_prompt", kv("vcs.repository.url.full", strVal("https://github.com/acme/other"))), codex, "test-scope") + require.NotNil(t, event) + assert.NotContains(t, event.Attributes, model.AICodeRepositoryAttribute) + + claude := newOtelResource(serviceResource("claude-code", + kv("pwd", strVal(dir)), + kv("vcs.repository.url.full", strVal("https://github.com/example-org/example-repo")), + ), model.AICodeOtelSourceClaudeCode) + event = p.parseLogRecord(claudeRecord("user_prompt", kv("prompt", strVal("hi"))), claude, "test-scope") + require.NotNil(t, event) + assert.NotContains(t, event.Attributes, model.AICodeRepositoryAttribute, "the resource's repository is removed too") + delta := metricsv1.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA + metrics := p.parseMetric(sumMetric("claude_code.active_time.total", delta, 30, kv("vcs.repository.url.full", strVal("https://github.com/acme/other"))), claude, "com.anthropic.claude_code") + require.Len(t, metrics, 1) + assert.NotContains(t, metrics[0].Attributes, model.AICodeRepositoryAttribute) + + assert.Nil(t, socketRepositoryResolver(model.ShellTimeConfig{AICodeOtel: &model.AICodeOtel{SendRepository: &off}})) + assert.NotNil(t, socketRepositoryResolver(model.ShellTimeConfig{})) +} + +// A record that names a working directory of its own doesn't get the resource folder's +// repository; one that names its repository keeps it. +func TestRepositoryNotFilledForAnotherWorkingDirectory(t *testing.T) { + dir := gitRepoWithOrigin(t, "git@github.com:acme/web.git") + p := NewAICodeOtelProcessor(model.ShellTimeConfig{}) + codex := newOtelResource(serviceResource("codex_cli_rs", kv("pwd", strVal(dir))), model.AICodeOtelSourceCodex) + codex.repository = p.resolveRepository(context.Background(), codex) + require.Equal(t, "https://github.com/acme/web", codex.repository) + + event := p.parseLogRecord(codexRecord("user_prompt", kv("pwd", strVal("/elsewhere"))), codex, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "/elsewhere", event.Pwd) + assert.NotContains(t, event.Attributes, model.AICodeRepositoryAttribute) + + event = p.parseLogRecord(codexRecord("user_prompt", kv("pwd", strVal(dir))), codex, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "https://github.com/acme/web", event.Attributes[model.AICodeRepositoryAttribute], "the same folder keeps it") + + event = p.parseLogRecord(codexRecord("user_prompt", kv("pwd", strVal(filepath.Join(dir, "src", "api")))), codex, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "https://github.com/acme/web", event.Attributes[model.AICodeRepositoryAttribute], "a subfolder of the work tree keeps it") + assert.False(t, insideDir(dir+"-other", dir), "a sibling with a longer name is outside") + + event = p.parseLogRecord(codexRecord("user_prompt", kv("pwd", strVal("/elsewhere")), kv("vcs.repository.url.full", strVal("https://github.com/acme/web"))), codex, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "https://github.com/acme/web", event.Attributes[model.AICodeRepositoryAttribute], "the record named the same repository itself") + + event = p.parseLogRecord(codexRecord("user_prompt", kv("pwd", strVal("/elsewhere")), kv("vcs.repository.url.full", strVal("https://github.com/acme/other"))), codex, "test-scope") + require.NotNil(t, event) + assert.Equal(t, "https://github.com/acme/other", event.Attributes[model.AICodeRepositoryAttribute], "the record's own repository stays") +} diff --git a/daemon/aicode_otel_traces_test.go b/daemon/aicode_otel_traces_test.go index e238db8..869e118 100644 --- a/daemon/aicode_otel_traces_test.go +++ b/daemon/aicode_otel_traces_test.go @@ -271,3 +271,24 @@ func TestAICodeOtelServer_TraceExportRoundTrip(t *testing.T) { assert.Equal(t, "claude-opus-5-5", got.Spans[1].Attributes["model"]) assert.Equal(t, int64(v2TestTimeNano)+int64(5*time.Millisecond), got.Spans[1].StartTimeUnixNano, "nanoseconds survive JSON") } + +// With aiCodeOtel.sendRepository off, spans and their events lose the repository too. +func TestDropSpanRepository(t *testing.T) { + s := claudeSpan("claude_code.tool", testRootID, nil, 0, time.Second, + kv(model.AICodeRepositoryAttribute, strVal("https://github.com/acme/web")), + kv("tool_name", strVal("Bash")), + ) + s.Events = []*tracev1.Span_Event{{ + Name: "tool.output", + Attributes: []*commonv1.KeyValue{kv(model.AICodeRepositoryAttribute, strVal("https://github.com/acme/web"))}, + }} + span := parseTestSpan(t, claudeTestResource(), s) + require.NotNil(t, span) + require.Contains(t, span.Attributes, model.AICodeRepositoryAttribute) + + dropSpanRepository(span) + assert.NotContains(t, span.Attributes, model.AICodeRepositoryAttribute) + assert.Equal(t, "Bash", span.Attributes["tool_name"]) + require.Len(t, span.Events, 1) + assert.NotContains(t, span.Events[0].Attributes, model.AICodeRepositoryAttribute) +} diff --git a/daemon/project_migration.go b/daemon/project_migration.go new file mode 100644 index 0000000..87947f9 --- /dev/null +++ b/daemon/project_migration.go @@ -0,0 +1,97 @@ +package daemon + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "os" + "path/filepath" + "time" + + "github.com/malamtime/cli/model" +) + +// projectMigrationDelay keeps the daemon's one-time project migration out of its startup. +const projectMigrationDelay = 2 * time.Minute + +// RunProjectMigrationOnce moves this machine's folder projects into their git repositories' +// projects, once per machine (see model.MigrateProjectRepositories): sessions recorded before +// the daemon named repositories are grouped by folder on the server, and only this machine can +// tell which repository a folder is a clone of. It runs in the background a while after start +// and leaves a marker when it is done; a server that doesn't support it yet, a failure, a list +// it didn't get through, a folder git couldn't answer for, or a machine without a host name of +// its own leaves none, so the next start tries again. `shelltime cc projects` runs it by hand. +func RunProjectMigrationOnce(ctx context.Context, cfg model.ShellTimeConfig) { + runProjectMigrationOnce(ctx, cfg, projectMigrationDelay, model.ProjectMigrationMarkerPath()) +} + +// projectMigrationHosts names this machine for the migration; tests replace it. +var projectMigrationHosts = func() []string { + return model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) +} + +type projectMigrationMarker struct { + MigratedAt time.Time `json:"migratedAt"` + Checked int `json:"checked"` + Linked int `json:"linked"` + Sessions int `json:"sessions"` +} + +func runProjectMigrationOnce(ctx context.Context, cfg model.ShellTimeConfig, delay time.Duration, markerPath string) { + if cfg.Token == "" || !cfg.SendsRepository() { + return + } + if _, err := os.Stat(markerPath); err == nil { + return + } + select { + case <-ctx.Done(): + return + case <-time.After(delay): + } + + endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint} + hosts := projectMigrationHosts() + if len(hosts) == 0 { + // Only names many machines share (localhost, ...): nothing to ask about, and no marker, + // so a real name (a later `cc install`, a renamed host) is picked up on another start. + slog.Debug("Project migration skipped: this machine has no host name of its own") + return + } + result, err := model.MigrateProjectRepositories(ctx, endpoint, hosts, model.NewGitRepositoryResolver(time.Hour), false) + if err != nil { + var statusErr *model.HTTPStatusError + if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusNotFound { + slog.Debug("Project migration skipped: the server can't group projects by repository yet") + return + } + slog.Warn("Project migration failed", slog.Any("err", err)) + return + } + + if result.Complete() { + marker, _ := json.Marshal(projectMigrationMarker{ + MigratedAt: time.Now().UTC(), + Checked: result.Checked, + Linked: len(result.Linked), + Sessions: result.Sessions, + }) + werr := os.MkdirAll(filepath.Dir(markerPath), 0o700) + if werr == nil { + werr = os.WriteFile(markerPath, marker, 0o600) + } + if werr != nil { + slog.Warn("Failed to write the project migration marker; it runs again on the next start", slog.Any("err", werr)) + } + } + slog.Info("Project migration finished", + slog.Int("checked", result.Checked), + slog.Int("linked", len(result.Linked)), + slog.Int("sessions", result.Sessions), + slog.Int("missing", result.Missing), + slog.Int("notRepositories", result.NotRepositories), + slog.Int("unchecked", result.Unchecked), + slog.Bool("truncated", result.Truncated)) +} diff --git a/daemon/project_migration_test.go b/daemon/project_migration_test.go new file mode 100644 index 0000000..568948c --- /dev/null +++ b/daemon/project_migration_test.go @@ -0,0 +1,123 @@ +package daemon + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync/atomic" + "testing" + + "github.com/malamtime/cli/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// withMigrationHosts names this machine for the migration in a test. +func withMigrationHosts(t *testing.T, hosts ...string) { + t.Helper() + original := projectMigrationHosts + projectMigrationHosts = func() []string { return hosts } + t.Cleanup(func() { projectMigrationHosts = original }) +} + +func TestRunProjectMigrationOnce(t *testing.T) { + withMigrationHosts(t, "mbp") + dir := gitRepoWithOrigin(t, "git@github.com:acme/web.git") + var requests atomic.Int32 + var moved []model.ProjectRepository + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + switch r.URL.Path { + case "/api/v1/cc/projects/unresolved": + _ = json.NewEncoder(w).Encode(map[string]any{"projects": []map[string]any{{"host": "mbp", "pwd": dir, "sessions": 2}}}) + case "/api/v1/cc/projects/repositories": + var body struct { + Projects []model.ProjectRepository `json:"projects"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + moved = body.Projects + _ = json.NewEncoder(w).Encode(map[string]int{"updated": 2}) + } + })) + t.Cleanup(server.Close) + cfg := model.ShellTimeConfig{Token: "tok", APIEndpoint: server.URL} + marker := filepath.Join(t.TempDir(), model.ProjectMigrationMarkerFile) + + runProjectMigrationOnce(context.Background(), cfg, 0, marker) + require.Equal(t, []model.ProjectRepository{{Host: "mbp", Pwd: dir, Repository: "https://github.com/acme/web"}}, moved) + data, err := os.ReadFile(marker) + require.NoError(t, err) + var written projectMigrationMarker + require.NoError(t, json.Unmarshal(data, &written)) + assert.Equal(t, projectMigrationMarker{MigratedAt: written.MigratedAt, Checked: 1, Linked: 1, Sessions: 2}, written) + + runProjectMigrationOnce(context.Background(), cfg, 0, marker) + assert.Equal(t, int32(2), requests.Load(), "with the marker in place nothing is asked again") +} + +// A machine with only a host name many machines share asks nothing and leaves no marker, so a +// real name (a later `cc install`, a renamed host) is picked up on another start. +func TestRunProjectMigrationOnceWithoutHosts(t *testing.T) { + withMigrationHosts(t) + var requests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + })) + t.Cleanup(server.Close) + marker := filepath.Join(t.TempDir(), model.ProjectMigrationMarkerFile) + + runProjectMigrationOnce(context.Background(), model.ShellTimeConfig{Token: "tok", APIEndpoint: server.URL}, 0, marker) + assert.NoFileExists(t, marker) + assert.Zero(t, requests.Load()) +} + +func TestRunProjectMigrationOnceRetriesATruncatedList(t *testing.T) { + withMigrationHosts(t, "mbp") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"projects": []any{}, "truncated": true}) + })) + t.Cleanup(server.Close) + marker := filepath.Join(t.TempDir(), model.ProjectMigrationMarkerFile) + + runProjectMigrationOnce(context.Background(), model.ShellTimeConfig{Token: "tok", APIEndpoint: server.URL}, 0, marker) + assert.NoFileExists(t, marker, "the rest of the list is checked on the next start") +} + +func TestRunProjectMigrationOnceSurvivesAnUnwritableMarker(t *testing.T) { + withMigrationHosts(t, "mbp") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"projects": []any{}}) + })) + t.Cleanup(server.Close) + parent := filepath.Join(t.TempDir(), "file") + require.NoError(t, os.WriteFile(parent, nil, 0o600)) + marker := filepath.Join(parent, model.ProjectMigrationMarkerFile) + + assert.NotPanics(t, func() { + runProjectMigrationOnce(context.Background(), model.ShellTimeConfig{Token: "tok", APIEndpoint: server.URL}, 0, marker) + }) + assert.NoFileExists(t, marker) +} + +func TestRunProjectMigrationOnceRetriesLater(t *testing.T) { + withMigrationHosts(t, "mbp") + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + t.Cleanup(server.Close) + marker := filepath.Join(t.TempDir(), model.ProjectMigrationMarkerFile) + + runProjectMigrationOnce(context.Background(), model.ShellTimeConfig{Token: "tok", APIEndpoint: server.URL}, 0, marker) + assert.NoFileExists(t, marker, "a server without the endpoints is asked again on the next start") + + runProjectMigrationOnce(context.Background(), model.ShellTimeConfig{APIEndpoint: server.URL}, 0, marker) + assert.NoFileExists(t, marker, "nothing happens without a token") + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + runProjectMigrationOnce(ctx, model.ShellTimeConfig{Token: "tok", APIEndpoint: server.URL}, projectMigrationDelay, marker) + assert.NoFileExists(t, marker, "stopping the daemon ends the wait") +} diff --git a/daemon/socket.go b/daemon/socket.go index 8ef7b16..a5d9c59 100644 --- a/daemon/socket.go +++ b/daemon/socket.go @@ -115,6 +115,9 @@ type SocketHandler struct { // configService, when set, is read again for each heartbeat message, so turning code // tracking on takes effect without restarting the daemon. configService model.ConfigService + // repos finds the git repository of a session_project message's directory. Nil sends + // none. + repos *model.GitRepositoryResolver } func NewSocketHandler(config *model.ShellTimeConfig, ch *GoChannel) *SocketHandler { @@ -124,9 +127,19 @@ func NewSocketHandler(config *model.ShellTimeConfig, ch *GoChannel) *SocketHandl stopChan: make(chan struct{}), ccInfoTimer: NewCCInfoTimerService(config), aiCloudOnly: model.IsAICloudOnly(*config, os.Getenv), + repos: socketRepositoryResolver(*config), } } +// socketRepositoryResolver is nil, so session_project messages name no repository, when +// aiCodeOtel.sendRepository is false. +func socketRepositoryResolver(config model.ShellTimeConfig) *model.GitRepositoryResolver { + if !config.SendsRepository() { + return nil + } + return model.NewGitRepositoryResolver(repositoryCacheTTL) +} + // SetConfigService makes heartbeat messages check the config on disk instead of the one // the daemon started with. func (p *SocketHandler) SetConfigService(cs model.ConfigService) { @@ -308,7 +321,7 @@ func (p *SocketHandler) handleConnection(conn net.Conn) { sessionID, _ := payload["sessionId"].(string) projectPath, _ := payload["projectPath"].(string) if sessionID != "" && projectPath != "" { - go model.SendSessionProjectUpdate(context.Background(), *p.config, sessionID, projectPath) + go p.sendSessionProject(sessionID, projectPath) slog.Debug("session_project update dispatched", slog.String("sessionId", sessionID)) } } @@ -319,6 +332,20 @@ func (p *SocketHandler) handleConnection(conn net.Conn) { } } +// sendSessionProject posts a Claude Code session's working directory, with the repository it +// belongs to, so the server can put the session in that repository's project. The statusline +// sends the directory on every render; the resolver answers repeats from its cache. +func (p *SocketHandler) sendSessionProject(sessionID, projectPath string) { + ctx := context.Background() + var repository string + if p.repos != nil { + repository = p.repos.Resolve(ctx, projectPath).URL + } + if err := model.SendSessionProjectUpdate(ctx, *p.config, sessionID, projectPath, repository); err != nil { + slog.Debug("session_project update failed", slog.String("sessionId", sessionID), slog.Any("err", err)) + } +} + func (p *SocketHandler) handleSessionPullRequests(msg SocketMessage) { buf, err := json.Marshal(msg.Payload) if err != nil { diff --git a/daemon/socket_extra_test.go b/daemon/socket_extra_test.go index 81ccc3f..c56b8af 100644 --- a/daemon/socket_extra_test.go +++ b/daemon/socket_extra_test.go @@ -237,6 +237,33 @@ func TestSocketHandler_SessionProject(t *testing.T) { }) } +// The daemon sends the repository the statusline's directory belongs to along with the path. +func TestSocketHandler_SessionProjectSendsRepository(t *testing.T) { + dir := gitRepoWithOrigin(t, "git@github.com:acme/web.git") + got := make(chan map[string]interface{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]interface{} + _ = json.NewDecoder(r.Body).Decode(&body) + if r.URL.Path == "/api/v1/cc/session-project" { + got <- body + } + w.WriteHeader(http.StatusNoContent) + })) + t.Cleanup(server.Close) + + _, socketPath := startHandler(t, &model.ShellTimeConfig{Token: "tok", APIEndpoint: server.URL}) + SendSessionProject(socketPath, "sess-1", dir) + + select { + case body := <-got: + assert.Equal(t, "sess-1", body["sessionId"]) + assert.Equal(t, dir, body["projectPath"]) + assert.Equal(t, "https://github.com/acme/web", body["repository"]) + case <-time.After(5 * time.Second): + t.Fatal("daemon did not send the session project to the server") + } +} + func TestSocketHandler_SessionPullRequestsSendsToServer(t *testing.T) { type request struct { path, auth string diff --git a/model/aicode_backfill_codex.go b/model/aicode_backfill_codex.go index 09d521e..edcb4cd 100644 --- a/model/aicode_backfill_codex.go +++ b/model/aicode_backfill_codex.go @@ -50,6 +50,10 @@ type codexSessionMeta struct { Cwd string `json:"cwd"` CLIVersion string `json:"cli_version"` ModelProvider string `json:"model_provider"` + // Git is what Codex found about the working directory when the session started. + Git *struct { + RepositoryURL string `json:"repository_url"` + } `json:"git"` } type codexTurnContext struct { @@ -125,6 +129,7 @@ type codexFileState struct { path string sessionID string cwd string + repository string // canonical URL of the session's git remote, from session_meta cliVersion string provider string metaTs time.Time @@ -194,6 +199,7 @@ func ParseCodexRollouts(roots []string, opts BackfillOptions) (*BackfillParseRes s.Events[i].Pwd = meta.cwd s.Events[i].AppVersion = meta.cliVersion } + s.Repository = meta.repository finalizeBackfillSession(s) if len(s.Events) > 0 { sessions = append(sessions, s) @@ -309,6 +315,9 @@ func (p *codexParser) handleSessionMeta(st *codexFileState, raw json.RawMessage, } st.metaTs = ts st.cwd = meta.Cwd + if meta.Git != nil { + st.repository, _ = CanonicalRepositoryURL(meta.Git.RepositoryURL) + } st.cliVersion = meta.CLIVersion st.provider = meta.ModelProvider } diff --git a/model/aicode_backfill_codex_test.go b/model/aicode_backfill_codex_test.go index 773b251..7d0673a 100644 --- a/model/aicode_backfill_codex_test.go +++ b/model/aicode_backfill_codex_test.go @@ -61,7 +61,7 @@ func writeCodexFixtures(t *testing.T) string { shellArgs := mustJSON(t, obj{"command": []any{"bash", "-lc", "go test ./..."}, "workdir": "/tmp/codex"}) writeJSONL(t, filepath.Join(day, "rollout-2026-09-10T10-00-00-"+codexSessionA+".jsonl"), - codexLine(codexTS(10, 0, 0), "session_meta", obj{"id": codexSessionA, "cwd": "/tmp/codex", "cli_version": "0.40.0", "model_provider": "openai", "originator": "codex_cli_rs"}), + codexLine(codexTS(10, 0, 0), "session_meta", obj{"id": codexSessionA, "cwd": "/tmp/codex", "cli_version": "0.40.0", "model_provider": "openai", "originator": "codex_cli_rs", "git": obj{"commit_hash": "abc123", "branch": "main", "repository_url": "git@github.com:acme/codex-app.git"}}), codexUserItem(codexTS(10, 0, 1), "\n /tmp/codex\n"), codexUserItem(codexTS(10, 0, 1), "fix the tests"), codexLine(codexTS(10, 0, 1), "event_msg", obj{"type": "user_message", "message": "fix the tests", "images": []any{}}), @@ -113,6 +113,8 @@ func TestParseCodexRollouts(t *testing.T) { require.Len(t, res.Sessions, 3) a := sessionByID(t, res, codexSessionA) + assert.Equal(t, "https://github.com/acme/codex-app", a.Repository, "the repository Codex recorded at the start") + assert.Empty(t, sessionByID(t, res, codexSessionB).Repository) starts := eventsOfType(a, AICodeEventConversationStarts) require.Len(t, starts, 1) assert.Equal(t, "gpt-5-codex", starts[0].Model) diff --git a/model/aicode_backfill_common.go b/model/aicode_backfill_common.go index 4f0ef64..d58442e 100644 --- a/model/aicode_backfill_common.go +++ b/model/aicode_backfill_common.go @@ -3,6 +3,7 @@ package model import ( "bufio" "bytes" + "context" "crypto/sha256" "encoding/hex" "encoding/json" @@ -46,6 +47,34 @@ type BackfillSession struct { Start time.Time End time.Time Events []AICodeBackfillEvent + // Repository is the canonical URL of the git repository the session ran in, when its + // transcript recorded one (Codex does); AttachBackfillRepositories fills the rest. + Repository string +} + +// AttachBackfillRepositories names each session's git repository on its events, so the server +// puts the session in the repository's project rather than its folder's. A repository the +// transcript recorded comes first, since it was true when the session ran; otherwise the +// session's working directory is asked, if it still exists and is a clone. +func AttachBackfillRepositories(ctx context.Context, sessions []*BackfillSession, repos *GitRepositoryResolver) { + for _, s := range sessions { + if s.Repository == "" && repos != nil && len(s.Events) > 0 { + s.Repository = repos.Resolve(ctx, s.Events[0].Pwd).URL + } + if s.Repository == "" { + continue + } + for i := range s.Events { + e := &s.Events[i] + if _, ok := e.Attributes[AICodeRepositoryAttribute]; ok { + continue + } + if e.Attributes == nil { + e.Attributes = make(map[string]any, 1) + } + e.Attributes[AICodeRepositoryAttribute] = s.Repository + } + } } // BackfillParseResult is what a transcript parser found on disk. diff --git a/model/aicode_backfill_common_test.go b/model/aicode_backfill_common_test.go index 1bf7f23..6c16e78 100644 --- a/model/aicode_backfill_common_test.go +++ b/model/aicode_backfill_common_test.go @@ -1,6 +1,7 @@ package model import ( + "context" "fmt" "os" "path/filepath" @@ -141,3 +142,33 @@ func TestCollectJSONL(t *testing.T) { assert.Len(t, inRange, 1) assert.Equal(t, "recent.jsonl", filepath.Base(inRange[0])) } + +func TestAttachBackfillRepositories(t *testing.T) { + recorded := &BackfillSession{ + ID: "recorded", + Repository: "https://github.com/acme/recorded", + Events: []AICodeBackfillEvent{ + {Pwd: "/gone"}, + {Pwd: "/gone", Attributes: map[string]any{AICodeRepositoryAttribute: "https://github.com/acme/own"}}, + }, + } + dir := t.TempDir() + git := &fakeGit{root: dir, remotes: "origin", url: "https://github.com/acme/from-cwd.git"} + repos := NewGitRepositoryResolver(time.Minute) + repos.git = git.run + fromCwd := &BackfillSession{ID: "cwd", Events: []AICodeBackfillEvent{{Pwd: dir}, {Pwd: dir}}} + nowhere := &BackfillSession{ID: "nowhere", Events: []AICodeBackfillEvent{{Pwd: filepath.Join(dir, "missing")}}} + empty := &BackfillSession{ID: "empty"} + + AttachBackfillRepositories(context.Background(), []*BackfillSession{recorded, fromCwd, nowhere, empty}, repos) + + assert.Equal(t, "https://github.com/acme/recorded", recorded.Events[0].Attributes[AICodeRepositoryAttribute]) + assert.Equal(t, "https://github.com/acme/own", recorded.Events[1].Attributes[AICodeRepositoryAttribute], "an event's own value is kept") + assert.Equal(t, "https://github.com/acme/from-cwd", fromCwd.Repository) + for _, e := range fromCwd.Events { + assert.Equal(t, "https://github.com/acme/from-cwd", e.Attributes[AICodeRepositoryAttribute]) + } + assert.Empty(t, nowhere.Repository) + assert.Nil(t, nowhere.Events[0].Attributes) + assert.Equal(t, 3, git.calls, "the recorded repository needs no git call") +} diff --git a/model/aicode_backfill_types.go b/model/aicode_backfill_types.go index 0e17502..fee32f3 100644 --- a/model/aicode_backfill_types.go +++ b/model/aicode_backfill_types.go @@ -71,6 +71,10 @@ type AICodeBackfillEvent struct { UserName string `json:"userName,omitempty"` MachineName string `json:"machineName,omitempty"` TeamID string `json:"teamId,omitempty"` + + // Attributes carries what has no field of its own: the session's git repository + // (AICodeRepositoryAttribute). + Attributes map[string]any `json:"attributes,omitempty"` } // AICodeBackfillRequest is the body of POST /api/v1/cc/backfill. diff --git a/model/aicode_otel_claude_settings.go b/model/aicode_otel_claude_settings.go index a392bbb..d589c4f 100644 --- a/model/aicode_otel_claude_settings.go +++ b/model/aicode_otel_claude_settings.go @@ -9,6 +9,7 @@ import ( "os" "os/user" "path/filepath" + "strings" "github.com/gookit/color" ) @@ -229,6 +230,30 @@ func (s *ClaudeSettingsAICodeOtelEnvService) StatusLineCommand() (string, error) return settings.StatusLine.Command, nil } +// ResourceMachineName returns the machine.name in the OTEL_RESOURCE_ATTRIBUTES of settings.json: +// the host name `cc install` wrote there, which Claude Code reports its sessions under even after +// the machine's name changes. Empty when it isn't set or can't be read. +func (s *ClaudeSettingsAICodeOtelEnvService) ResourceMachineName() string { + data, _, err := s.readSettings() + if err != nil || data == nil { + return "" + } + var settings struct { + Env map[string]any `json:"env"` + } + if err := json.Unmarshal(data, &settings); err != nil { + return "" + } + attrs, _ := settings.Env["OTEL_RESOURCE_ATTRIBUTES"].(string) + for _, pair := range strings.Split(attrs, ",") { + key, value, ok := strings.Cut(pair, "=") + if ok && strings.TrimSpace(key) == "machine.name" { + return strings.TrimSpace(value) + } + } + return "" +} + // readSettings returns the settings file content and mode. A missing file yields nil data. func (s *ClaudeSettingsAICodeOtelEnvService) readSettings() ([]byte, os.FileMode, error) { info, err := os.Stat(s.settingsPath) diff --git a/model/api_project_repositories.go b/model/api_project_repositories.go new file mode 100644 index 0000000..9068631 --- /dev/null +++ b/model/api_project_repositories.go @@ -0,0 +1,97 @@ +package model + +import ( + "context" + "net/http" + "time" +) + +// Server limits of the project repository endpoints. +const ( + ProjectRepositoriesMaxHosts = 20 + ProjectRepositoriesMaxProjects = 500 +) + +// UnresolvedProject is a project the server still groups by folder: sessions on Host that ran in +// Pwd and have no git repository. +type UnresolvedProject struct { + Host string `json:"host"` + Pwd string `json:"pwd"` + Sessions int `json:"sessions"` +} + +// ProjectRepository moves the sessions of a folder project into the project of the git +// repository the folder is a clone of. +type ProjectRepository struct { + Host string `json:"host"` + Pwd string `json:"pwd"` + Repository string `json:"repository"` // canonical URL, see CanonicalRepositoryURL +} + +type unresolvedProjectsRequest struct { + Hosts []string `json:"hosts"` + // After is the last project of the previous page. + After *unresolvedProjectCursor `json:"after,omitempty"` +} + +type unresolvedProjectCursor struct { + Host string `json:"host"` + Pwd string `json:"pwd"` +} + +type unresolvedProjectsResponse struct { + Projects []UnresolvedProject `json:"projects"` + // Truncated is true when more folders follow this page. + Truncated bool `json:"truncated"` +} + +type projectRepositoriesRequest struct { + Projects []ProjectRepository `json:"projects"` +} + +type projectRepositoriesResponse struct { + Updated int `json:"updated"` +} + +// FetchUnresolvedProjects lists a page of the folder projects of the given hosts, the names this +// machine has reported its sessions under, by machine and folder. after is the last project of +// the previous page (nil for the first); truncated is true when more follow. +func FetchUnresolvedProjects(ctx context.Context, endpoint Endpoint, hosts []string, after *UnresolvedProject) (projects []UnresolvedProject, truncated bool, err error) { + ctx, span := modelTracer.Start(ctx, "project_repositories.unresolved") + defer span.End() + + req := &unresolvedProjectsRequest{Hosts: hosts} + if after != nil { + req.After = &unresolvedProjectCursor{Host: after.Host, Pwd: after.Pwd} + } + var resp unresolvedProjectsResponse + err = SendHTTPRequestJSON(HTTPRequestOptions[*unresolvedProjectsRequest, unresolvedProjectsResponse]{ + Context: ctx, + Endpoint: endpoint, + Method: http.MethodPost, + Path: "/api/v1/cc/projects/unresolved", + Payload: req, + Response: &resp, + Timeout: 30 * time.Second, + }) + return resp.Projects, resp.Truncated, err +} + +// SendProjectRepositories moves folder projects into their repositories' projects and returns +// how many sessions moved. +func SendProjectRepositories(ctx context.Context, endpoint Endpoint, projects []ProjectRepository) (int, error) { + ctx, span := modelTracer.Start(ctx, "project_repositories.send") + defer span.End() + + var resp projectRepositoriesResponse + err := SendHTTPRequestJSON(HTTPRequestOptions[*projectRepositoriesRequest, projectRepositoriesResponse]{ + Context: ctx, + Endpoint: endpoint, + Method: http.MethodPost, + Path: "/api/v1/cc/projects/repositories", + Payload: &projectRepositoriesRequest{Projects: projects}, + Response: &resp, + Timeout: 30 * time.Second, + }) + return resp.Updated, err +} diff --git a/model/api_senders_test.go b/model/api_senders_test.go index ac586e8..9837bb3 100644 --- a/model/api_senders_test.go +++ b/model/api_senders_test.go @@ -94,11 +94,12 @@ func TestSendSessionProjectUpdate(t *testing.T) { defer server.Close() cfg := ShellTimeConfig{Token: "t", APIEndpoint: server.URL} - err := SendSessionProjectUpdate(context.Background(), cfg, "sess-1", "/home/me/proj") + err := SendSessionProjectUpdate(context.Background(), cfg, "sess-1", "/home/me/proj", "https://github.com/me/proj") require.NoError(t, err) assert.Equal(t, "/api/v1/cc/session-project", gotPath) assert.Equal(t, "sess-1", body.SessionID) assert.Equal(t, "/home/me/proj", body.ProjectPath) + assert.Equal(t, "https://github.com/me/proj", body.Repository) }) t.Run("error path returns error", func(t *testing.T) { @@ -109,7 +110,7 @@ func TestSendSessionProjectUpdate(t *testing.T) { defer server.Close() cfg := ShellTimeConfig{Token: "t", APIEndpoint: server.URL} - err := SendSessionProjectUpdate(context.Background(), cfg, "s", "p") + err := SendSessionProjectUpdate(context.Background(), cfg, "s", "p", "") require.Error(t, err) assert.Equal(t, "boom", err.Error()) }) diff --git a/model/api_session_project.go b/model/api_session_project.go index 40d1fb2..c028530 100644 --- a/model/api_session_project.go +++ b/model/api_session_project.go @@ -9,12 +9,16 @@ import ( type sessionProjectRequest struct { SessionID string `json:"sessionId"` ProjectPath string `json:"projectPath"` + // Repository is the canonical URL of the git repository ProjectPath belongs to (see + // CanonicalRepositoryURL); empty outside a repository or without a remote. + Repository string `json:"repository,omitempty"` } type sessionProjectResponse struct{} -// SendSessionProjectUpdate sends a session-to-project path mapping to the server -func SendSessionProjectUpdate(ctx context.Context, config ShellTimeConfig, sessionID, projectPath string) error { +// SendSessionProjectUpdate sends a session's working directory, and the repository it belongs +// to when there is one, to the server, which fills them in on the session's events. +func SendSessionProjectUpdate(ctx context.Context, config ShellTimeConfig, sessionID, projectPath, repository string) error { ctx, span := modelTracer.Start(ctx, "session_project.send") defer span.End() @@ -30,6 +34,7 @@ func SendSessionProjectUpdate(ctx context.Context, config ShellTimeConfig, sessi Payload: &sessionProjectRequest{ SessionID: sessionID, ProjectPath: projectPath, + Repository: repository, }, Response: &resp, Timeout: 5 * time.Second, diff --git a/model/config.go b/model/config.go index d26b0a8..12d5f9c 100644 --- a/model/config.go +++ b/model/config.go @@ -176,7 +176,25 @@ func mergeConfig(base, local *ShellTimeConfig) { base.Exclude = local.Exclude } if local.AICodeOtel != nil { - base.AICodeOtel = local.AICodeOtel + // Field by field: a local file that only sets debug or the port must not turn the + // collector off or bring back the repository a base sendRepository: false keeps to itself + if base.AICodeOtel == nil { + base.AICodeOtel = &AICodeOtel{} + } + merged := *base.AICodeOtel + if local.AICodeOtel.Enabled != nil { + merged.Enabled = local.AICodeOtel.Enabled + } + if local.AICodeOtel.GRPCPort != 0 { + merged.GRPCPort = local.AICodeOtel.GRPCPort + } + if local.AICodeOtel.Debug != nil { + merged.Debug = local.AICodeOtel.Debug + } + if local.AICodeOtel.SendRepository != nil { + merged.SendRepository = local.AICodeOtel.SendRepository + } + base.AICodeOtel = &merged } if local.LogCleanup != nil { base.LogCleanup = local.LogCleanup diff --git a/model/config_test.go b/model/config_test.go index 98ebccd..373ec49 100644 --- a/model/config_test.go +++ b/model/config_test.go @@ -649,3 +649,24 @@ func TestConfigFilePathsAndValidate(t *testing.T) { assert.Error(t, ValidateConfigFile(localPath)) assert.Error(t, ValidateConfigFile(filepath.Join(dir, "missing.yaml"))) } + +// A local aiCodeOtel block that only sets debug keeps the base file's other settings, the +// repository opt-out included. +func TestLocalAICodeOtelMergesFieldByField(t *testing.T) { + tmpDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(tmpDir, "config.yaml"), []byte(`token: tok +aiCodeOtel: + enabled: true + grpcPort: 54100 + sendRepository: false`), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(tmpDir, "config.local.yaml"), []byte(`aiCodeOtel: + debug: true`), 0o644)) + + config, err := NewConfigService(tmpDir).ReadConfigFile(context.Background()) + require.NoError(t, err) + require.NotNil(t, config.AICodeOtel) + assert.True(t, *config.AICodeOtel.Enabled) + assert.Equal(t, 54100, config.AICodeOtel.GRPCPort) + assert.True(t, *config.AICodeOtel.Debug) + assert.False(t, config.SendsRepository()) +} diff --git a/model/git_repository.go b/model/git_repository.go new file mode 100644 index 0000000..fefcaa5 --- /dev/null +++ b/model/git_repository.go @@ -0,0 +1,436 @@ +package model + +import ( + "context" + "errors" + "io/fs" + "net/url" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "sync" + "time" +) + +// AICodeRepositoryAttribute is the OTEL attribute that names the git repository a coding agent +// ran in. Claude Code sets it itself (OTEL_METRICS_INCLUDE_REPOSITORY, which `cc install` +// turns on); the daemon and backfill add it from the working directory when a record lacks +// it. The server groups projects by the repository instead of the folder, so a renamed or +// moved clone, a worktree or a subfolder stays one project. +const AICodeRepositoryAttribute = "vcs.repository.url.full" + +// CanonicalRepositoryURL turns a git remote URL into https:///, the form Claude +// Code reports: scp-like (git@host:owner/repo.git), ssh://, git:// and http(s) remotes all +// become the same URL. Credentials, the port, a query, a fragment, trailing slashes and the +// .git suffix are dropped, and the host is lowercased; the path keeps its case. It returns +// false for a remote that is a local path or not a URL at all. +func CanonicalRepositoryURL(remote string) (string, bool) { + remote = strings.TrimSpace(remote) + if remote == "" || strings.ContainsAny(remote, "\\ \t\r\n") { + return "", false + } + + var host, path string + if i := strings.Index(remote, "://"); i >= 0 { + u, err := url.Parse(remote) + if err != nil { + return "", false + } + switch strings.ToLower(u.Scheme) { + case "https", "http", "ssh", "git", "git+ssh", "ssh+git": + default: + return "", false // file://, and anything git can't fetch from a host + } + host, path = u.Hostname(), u.Path + } else { + // scp-like: [user@]host:path. A colon after a slash is part of a local path. + colon := strings.Index(remote, ":") + if colon <= 0 || strings.Contains(remote[:colon], "/") { + return "", false + } + host = remote[:colon] + if at := strings.LastIndex(host, "@"); at >= 0 { + host = host[at+1:] + } + path = remote[colon+1:] + if unescaped, err := url.PathUnescape(path); err == nil { + path = unescaped + } + } + + host = strings.ToLower(strings.TrimSuffix(host, ".")) + // A one-letter "host" is a Windows drive (C:/repo), not a server. + if len(host) < 2 || strings.ContainsAny(host, "/@[]") { + return "", false + } + + segments := strings.FieldsFunc(path, func(r rune) bool { return r == '/' }) + if len(segments) > 0 { + last := len(segments) - 1 + segments[last] = strings.TrimSuffix(segments[last], ".git") + if segments[last] == "" { + segments = segments[:last] + } + } + if len(segments) == 0 || slices.Contains(segments, "..") || slices.Contains(segments, ".") { + return "", false + } + // Each segment is escaped again, so every spelling of a name ("My Project", "My%20Project", + // a non-ASCII name raw or escaped) gives one URL, and a %23 or %3F stays part of the name. + // The server escapes the same way (model.CanonicalRepositoryURL there). + for i, s := range segments { + segments[i] = url.PathEscape(s) + } + return "https://" + host + "/" + strings.Join(segments, "/"), true +} + +// GitRepository is what git says about a directory. +type GitRepository struct { + // Root is the top level of the work tree; empty when the directory isn't in one. + Root string + // URL is the canonical URL of the repository's remote (see CanonicalRepositoryURL); empty + // for a repository without a usable remote. + URL string +} + +const ( + // gitRepositoryTimeout bounds a whole lookup (up to three git runs), well under an OTLP + // exporter's timeout, since the daemon resolves on the export path. + gitRepositoryTimeout = 2 * time.Second + // gitRepositoryRetryAfter is how long a lookup that timed out or couldn't start git is + // remembered: long enough that a hung mount doesn't cost every export the whole budget, + // short enough that the directory is asked about again soon. + gitRepositoryRetryAfter = 30 * time.Second + // gitRepositoryGrace is how long past the budget a lookup is waited for. A stat or a git + // run stuck in the kernel (a hung network mount) ignores the context, so the waiting stops + // here instead and the directory counts as stuck until that lookup returns. + gitRepositoryGrace = 250 * time.Millisecond + gitRepositoryMaxEntries = 512 +) + +// gitExitError is git exiting with an error status: a definitive answer (not a work tree, no +// such remote), unlike a timeout, a signal, git failing to start or refusing a repository it +// doesn't trust (safe.directory), which say nothing about the directory and are not cached. +type gitExitError struct{ err error } + +func (e gitExitError) Error() string { return e.err.Error() } +func (e gitExitError) Unwrap() error { return e.err } + +// GitRepositoryResolver finds the repository a directory belongs to with the git CLI, and +// remembers answers for a while, negative ones included: the daemon asks for the same few +// directories on every OTEL export and statusline render. A definitive answer is kept for the +// resolver's TTL, one from a lookup that timed out or couldn't start git for +// gitRepositoryRetryAfter at most. Concurrent lookups of one directory share one run of git. +type GitRepositoryResolver struct { + ttl time.Duration + // timeout is the budget of one lookup, gitRepositoryTimeout unless a test sets it. + timeout time.Duration + // git runs git with args in dir; tests replace it. + git func(ctx context.Context, dir string, args ...string) (string, error) + now func() time.Time + + mu sync.Mutex + cache map[string]gitRepositoryEntry + inflight map[string]*gitRepositoryCall + // stuck holds directories whose lookup outlived its budget and hasn't returned yet; they get + // no second one meanwhile, so a hung mount costs one blocked thread, not one per retry. + stuck map[string]struct{} +} + +type gitRepositoryEntry struct { + repo GitRepository + definitive bool + expires time.Time +} + +type gitRepositoryAnswer struct { + repo GitRepository + definitive bool +} + +type gitRepositoryCall struct { + done chan struct{} + repo GitRepository + definitive bool +} + +// NewGitRepositoryResolver returns a resolver that keeps answers for ttl (0 keeps nothing). +func NewGitRepositoryResolver(ttl time.Duration) *GitRepositoryResolver { + return &GitRepositoryResolver{ + ttl: ttl, + timeout: gitRepositoryTimeout, + git: runGit, + now: time.Now, + cache: make(map[string]gitRepositoryEntry), + inflight: make(map[string]*gitRepositoryCall), + stuck: make(map[string]struct{}), + } +} + +var ( + gitBinaryMu sync.Mutex + gitBinary string + gitBinaryLookedAt time.Time +) + +// gitExecutable finds git, also where the daemon's limited PATH doesn't reach (Homebrew, +// /usr/local/bin), through the CommandService's fallback paths. A path found is kept; while +// none is, it looks again every gitRepositoryRetryAfter, so git installed after the daemon +// started is picked up, and runs the bare "git" meanwhile. +func gitExecutable() string { + gitBinaryMu.Lock() + defer gitBinaryMu.Unlock() + if gitBinary == "" && time.Since(gitBinaryLookedAt) >= gitRepositoryRetryAfter { + gitBinaryLookedAt = time.Now() + if path, err := NewCommandService().LookPath("git"); err == nil { + gitBinary = path + } + } + if gitBinary == "" { + return "git" + } + return gitBinary +} + +// runGit runs git without taking optional locks (it must never get in the way of the user's +// own git commands) and without prompting, under ctx's deadline. +func runGit(ctx context.Context, dir string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, gitExecutable(), append([]string{"-C", dir}, args...)...) + // Messages in English: gitExitIsAnswer reads them. + cmd.Env = append(os.Environ(), "GIT_OPTIONAL_LOCKS=0", "GIT_TERMINAL_PROMPT=0", "LC_ALL=C", "LANGUAGE=") + out, err := cmd.Output() + var exitErr *exec.ExitError + if err != nil && errors.As(err, &exitErr) && ctx.Err() == nil && gitExitIsAnswer(exitErr) { + return "", gitExitError{err} + } + return strings.TrimSpace(string(out)), err +} + +// gitExitIsAnswer reports whether git's error exit says something about the directory. Killed +// by a signal (ExitCode -1), or refusing a repository owned by someone else, it doesn't: the +// directory may well be a clone. +func gitExitIsAnswer(err *exec.ExitError) bool { + if err.ExitCode() < 0 { + return false + } + stderr := strings.ToLower(string(err.Stderr)) + return !strings.Contains(stderr, "dubious ownership") && + !strings.Contains(stderr, "safe.directory") && + !strings.Contains(stderr, "unsafe repository") +} + +// Resolve returns the repository dir belongs to. A directory that doesn't exist, isn't in a +// work tree or can't be read returns the zero GitRepository. +func (r *GitRepositoryResolver) Resolve(ctx context.Context, dir string) GitRepository { + repo, _ := r.Lookup(ctx, dir) + return repo +} + +// Lookup is Resolve, and also says whether the answer is definitive: false when git timed out or +// couldn't run (or ctx ended first), so the directory's repository is unknown rather than none. +func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepository, bool) { + dir = strings.TrimSpace(dir) + if dir == "" || !filepath.IsAbs(dir) { + return GitRepository{}, true + } + dir = filepath.Clean(dir) + if dir == string(filepath.Separator) { + return GitRepository{}, true + } + + r.mu.Lock() + if e, ok := r.cache[dir]; ok && r.now().Before(e.expires) { + r.mu.Unlock() + return e.repo, e.definitive + } + if _, ok := r.stuck[dir]; ok { + r.mu.Unlock() + return GitRepository{}, false + } + if call, ok := r.inflight[dir]; ok { + r.mu.Unlock() + select { + case <-call.done: + return call.repo, call.definitive + case <-ctx.Done(): + return GitRepository{}, false + } + } + call := &gitRepositoryCall{done: make(chan struct{})} + r.inflight[dir] = call + r.mu.Unlock() + + // The lookup belongs to no caller: one that gives up (its exporter went away) leaves it + // running for the others, and the budget bounds it instead. + go r.run(context.WithoutCancel(ctx), dir, call) + select { + case <-call.done: + return call.repo, call.definitive + case <-ctx.Done(): + return GitRepository{}, false + } +} + +// run looks dir up and publishes the answer to call. The lookup has its own goroutine because +// the budget can't interrupt a stat or a git run blocked in the kernel; past the budget (plus +// gitRepositoryGrace) the callers get "unknown" and the directory counts as stuck until the +// lookup returns. +func (r *GitRepositoryResolver) run(ctx context.Context, dir string, call *gitRepositoryCall) { + defer close(call.done) + answers := make(chan gitRepositoryAnswer, 1) + timeout := r.timeout + go func() { + lookupCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + a := gitRepositoryAnswer{} + a.repo, a.definitive = r.lookup(lookupCtx, dir) + answers <- a + }() + timer := time.NewTimer(timeout + gitRepositoryGrace) + defer timer.Stop() + select { + case a := <-answers: + r.finish(dir, call, a.repo, a.definitive) + case <-timer.C: + r.mu.Lock() + r.stuck[dir] = struct{}{} + r.mu.Unlock() + r.finish(dir, call, GitRepository{}, false) + r.abandon(dir, answers) + } +} + +// abandon keeps the answer of a lookup that outlived its budget for whoever asks next, and +// clears the directory's stuck mark then. +func (r *GitRepositoryResolver) abandon(dir string, answers <-chan gitRepositoryAnswer) { + go func() { + a := <-answers + r.mu.Lock() + defer r.mu.Unlock() + delete(r.stuck, dir) + if ttl := r.entryTTL(a.definitive); ttl > 0 && len(r.cache) < gitRepositoryMaxEntries { + r.cache[dir] = gitRepositoryEntry{repo: a.repo, definitive: a.definitive, expires: r.now().Add(ttl)} + } + }() +} + +// finish publishes a lookup's answer to the cache and to the callers waiting on it. +func (r *GitRepositoryResolver) finish(dir string, call *gitRepositoryCall, repo GitRepository, definitive bool) { + r.mu.Lock() + defer r.mu.Unlock() + call.repo, call.definitive = repo, definitive + delete(r.inflight, dir) + // An abandoned lookup that answered in the meantime has cached its answer; "unknown" never + // replaces it. + if e, ok := r.cache[dir]; ok && !definitive && e.definitive && r.now().Before(e.expires) { + return + } + if ttl := r.entryTTL(definitive); ttl > 0 { + now := r.now() + if len(r.cache) >= gitRepositoryMaxEntries { + for k, e := range r.cache { + if !now.Before(e.expires) { + delete(r.cache, k) + } + } + if len(r.cache) >= gitRepositoryMaxEntries { + clear(r.cache) + } + } + r.cache[dir] = gitRepositoryEntry{repo: repo, definitive: definitive, expires: now.Add(ttl)} + } +} + +// dirState is what a stat of a project's folder said. +type dirState int + +const ( + dirExists dirState = iota + dirMissing // nothing there, or not a directory + dirUnknown // the stat failed some other way (permissions, I/O) + dirTimedOut // the stat didn't return in time, as on a hung network mount +) + +// statDir stats dir, giving up after timeout: on a hung network mount the stat blocks in the +// kernel, where no context reaches it. Tests replace it. +var statDir = func(dir string, timeout time.Duration) dirState { + result := make(chan dirState, 1) + go func() { + info, err := os.Stat(dir) + switch { + case err == nil && info.IsDir(): + result <- dirExists + case err == nil, errors.Is(err, fs.ErrNotExist): + result <- dirMissing + default: + result <- dirUnknown + } + }() + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case state := <-result: + return state + case <-timer.C: + return dirTimedOut + } +} + +// entryTTL is how long an answer is kept. +func (r *GitRepositoryResolver) entryTTL(definitive bool) time.Duration { + if definitive { + return r.ttl + } + return min(r.ttl, gitRepositoryRetryAfter) +} + +// lookup asks git about dir. definitive is false when git timed out or couldn't run, so the +// answer isn't cached and the next record asks again. +func (r *GitRepositoryResolver) lookup(ctx context.Context, dir string) (repo GitRepository, definitive bool) { + answered := func(err error) bool { + var exit gitExitError + return errors.As(err, &exit) + } + if info, err := os.Stat(dir); err != nil || !info.IsDir() { + return GitRepository{}, true + } + root, err := r.git(ctx, dir, "rev-parse", "--show-toplevel") + if err != nil || root == "" { + return GitRepository{}, err == nil || answered(err) + } + repo = GitRepository{Root: filepath.Clean(root)} + + remotes, err := r.git(ctx, dir, "remote") + if err != nil { + return repo, answered(err) + } + name := pickGitRemote(strings.Fields(remotes)) + if name == "" { + return repo, true + } + // get-url applies the user's url..insteadOf rewrites, unlike reading the config. + raw, err := r.git(ctx, dir, "remote", "get-url", name) + if err != nil { + return repo, answered(err) + } + if u, ok := CanonicalRepositoryURL(raw); ok { + repo.URL = u + } + return repo, true +} + +// pickGitRemote prefers origin, the remote a clone creates and the one the user pushes to (so a +// fork is its own project), then upstream, then the first remote by name. +func pickGitRemote(remotes []string) string { + for _, preferred := range []string{"origin", "upstream"} { + if slices.Contains(remotes, preferred) { + return preferred + } + } + if len(remotes) == 0 { + return "" + } + return slices.Min(remotes) +} diff --git a/model/git_repository_test.go b/model/git_repository_test.go new file mode 100644 index 0000000..f01d0af --- /dev/null +++ b/model/git_repository_test.go @@ -0,0 +1,378 @@ +package model + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCanonicalRepositoryURL(t *testing.T) { + tests := []struct { + remote string + want string + }{ + {"https://github.com/shelltime/cli.git", "https://github.com/shelltime/cli"}, + {"https://github.com/shelltime/cli", "https://github.com/shelltime/cli"}, + {"https://github.com/shelltime/cli/", "https://github.com/shelltime/cli"}, + {"http://GitHub.com/ShellTime/CLI.git", "https://github.com/ShellTime/CLI"}, + {"https://x-access-token:ghp_secret@github.com/acme/web.git", "https://github.com/acme/web"}, + {"https://user@gitlab.example.com:8443/group/sub/repo.git?ref=1#frag", "https://gitlab.example.com/group/sub/repo"}, + {"git@github.com:shelltime/cli.git", "https://github.com/shelltime/cli"}, + {"git@github.com:/shelltime/cli.git", "https://github.com/shelltime/cli"}, + {"github.com:shelltime/cli", "https://github.com/shelltime/cli"}, + {"ssh://git@github.com/shelltime/cli.git", "https://github.com/shelltime/cli"}, + {"ssh://git@gitea.local:2222/team/app", "https://gitea.local/team/app"}, + {"git+ssh://git@github.com/shelltime/cli.git", "https://github.com/shelltime/cli"}, + {"git://git.kernel.org/pub/scm/git/git.git", "https://git.kernel.org/pub/scm/git/git"}, + {" https://github.com/a/b.git\n", "https://github.com/a/b"}, + } + for _, tt := range tests { + t.Run(tt.remote, func(t *testing.T) { + got, ok := CanonicalRepositoryURL(tt.remote) + require.True(t, ok) + assert.Equal(t, tt.want, got) + }) + } +} + +// Names are escaped the same way whatever the remote's form, like the server does. +func TestCanonicalRepositoryURLEscapesNames(t *testing.T) { + for remote, want := range map[string]string{ + "https://dev.azure.com/org/My%20Project/_git/repo": "https://dev.azure.com/org/My%20Project/_git/repo", + "https://example.com/acme/repo%23one.git": "https://example.com/acme/repo%23one", + "https://github.com/acme/Ⱥ": "https://github.com/acme/%C8%BA", + "git@github.com:acme/%c8%ba.git": "https://github.com/acme/%C8%BA", + } { + got, ok := CanonicalRepositoryURL(remote) + require.True(t, ok, remote) + assert.Equal(t, want, got, remote) + } +} + +func TestCanonicalRepositoryURLRejectsLocalRemotes(t *testing.T) { + for _, remote := range []string{ + "", + "/srv/git/repo.git", + "../other", + "./repo:with-colon", + "file:///srv/git/repo.git", + "C:/repos/app", + `C:\repos\app`, + "https://github.com", + "https://github.com/.git", + "git@github.com:", + "https://github.com/a/../b", + "ftp://example.com/a/b", + "has space:repo", + } { + t.Run(remote, func(t *testing.T) { + _, ok := CanonicalRepositoryURL(remote) + assert.False(t, ok) + }) + } +} + +func TestPickGitRemote(t *testing.T) { + assert.Equal(t, "origin", pickGitRemote([]string{"upstream", "origin", "fork"})) + assert.Equal(t, "upstream", pickGitRemote([]string{"zeta", "upstream"})) + assert.Equal(t, "alpha", pickGitRemote([]string{"zeta", "alpha"})) + assert.Equal(t, "", pickGitRemote(nil)) +} + +// fakeGit answers like git for the directories it knows and counts the calls. +type fakeGit struct { + root string + remotes string + url string + calls int +} + +func (f *fakeGit) run(_ context.Context, dir string, args ...string) (string, error) { + f.calls++ + switch { + case args[0] == "rev-parse": + if f.root == "" { + return "", gitExitError{errors.New("not a git repository")} + } + return f.root, nil + case len(args) == 1 && args[0] == "remote": + return f.remotes, nil + case len(args) == 3 && args[1] == "get-url": + return f.url, nil + } + return "", errors.New("unexpected git call") +} + +func TestGitRepositoryResolverCachesAnswers(t *testing.T) { + dir := t.TempDir() + git := &fakeGit{root: dir, remotes: "origin\n", url: "git@github.com:acme/web.git"} + now := time.Unix(1_700_000_000, 0) + r := NewGitRepositoryResolver(time.Minute) + r.git = git.run + r.now = func() time.Time { return now } + + want := GitRepository{Root: dir, URL: "https://github.com/acme/web"} + assert.Equal(t, want, r.Resolve(context.Background(), dir)) + assert.Equal(t, 3, git.calls) + + assert.Equal(t, want, r.Resolve(context.Background(), dir+"/"), "a trailing slash is the same directory") + assert.Equal(t, 3, git.calls, "the second lookup is served from the cache") + + now = now.Add(2 * time.Minute) + git.url = "https://github.com/acme/renamed.git" + assert.Equal(t, "https://github.com/acme/renamed", r.Resolve(context.Background(), dir).URL) + assert.Equal(t, 6, git.calls, "an expired answer is looked up again") +} + +func TestGitRepositoryResolverCachesNegativeAnswers(t *testing.T) { + dir := t.TempDir() + git := &fakeGit{} + r := NewGitRepositoryResolver(time.Minute) + r.git = git.run + + assert.Equal(t, GitRepository{}, r.Resolve(context.Background(), dir)) + assert.Equal(t, GitRepository{}, r.Resolve(context.Background(), dir)) + assert.Equal(t, 1, git.calls) +} + +// A timeout, or git failing to start, says nothing about the directory: it is kept only briefly +// and reported as unknown, instead of serving a cached "no repository" for the whole TTL. +func TestGitRepositoryResolverDoesNotCacheTransientFailures(t *testing.T) { + dir := t.TempDir() + calls := 0 + failing := true + now := time.Unix(1_700_000_000, 0) + r := NewGitRepositoryResolver(time.Hour) + r.now = func() time.Time { return now } + r.git = func(ctx context.Context, d string, args ...string) (string, error) { + calls++ + if failing { + return "", context.DeadlineExceeded + } + return (&fakeGit{root: dir, remotes: "origin", url: "https://github.com/acme/web"}).run(ctx, d, args...) + } + + repo, definitive := r.Lookup(context.Background(), dir) + assert.Equal(t, GitRepository{}, repo) + assert.False(t, definitive, "unknown, not no repository") + failing = false + _, definitive = r.Lookup(context.Background(), dir) + assert.False(t, definitive) + assert.Equal(t, 1, calls, "a hung directory doesn't cost every caller the whole budget") + + now = now.Add(gitRepositoryRetryAfter + time.Second) + repo, definitive = r.Lookup(context.Background(), dir) + assert.Equal(t, "https://github.com/acme/web", repo.URL) + assert.True(t, definitive) + assert.Equal(t, 4, calls, "asked again soon after") + + now = now.Add(30 * time.Minute) + r.Resolve(context.Background(), dir) + assert.Equal(t, 4, calls, "a definitive answer is kept for the TTL") +} + +// Concurrent lookups of one directory share one run of git. +func TestGitRepositoryResolverSharesConcurrentLookups(t *testing.T) { + dir := t.TempDir() + release := make(chan struct{}) + var mu sync.Mutex + calls := 0 + r := NewGitRepositoryResolver(time.Minute) + r.git = func(ctx context.Context, d string, args ...string) (string, error) { + mu.Lock() + calls++ + mu.Unlock() + <-release + return (&fakeGit{root: dir, remotes: "origin", url: "https://github.com/acme/web"}).run(ctx, d, args...) + } + + var wg sync.WaitGroup + results := make([]GitRepository, 5) + for i := range results { + wg.Add(1) + go func(i int) { + defer wg.Done() + results[i] = r.Resolve(context.Background(), dir) + }(i) + } + time.Sleep(50 * time.Millisecond) + close(release) + wg.Wait() + + for _, got := range results { + assert.Equal(t, "https://github.com/acme/web", got.URL) + } + assert.Equal(t, 3, calls, "one lookup: rev-parse, remote, get-url") +} + +// A caller that gives up returns at once; the lookup it started still finishes for the others. +func TestGitRepositoryResolverWaiterGivesUp(t *testing.T) { + dir := t.TempDir() + release := make(chan struct{}) + r := NewGitRepositoryResolver(time.Minute) + r.git = func(ctx context.Context, d string, args ...string) (string, error) { + <-release + return (&fakeGit{root: dir, remotes: "origin", url: "https://github.com/acme/web"}).run(ctx, d, args...) + } + + first := make(chan GitRepository) + go func() { first <- r.Resolve(context.Background(), dir) }() + time.Sleep(20 * time.Millisecond) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + assert.Equal(t, GitRepository{}, r.Resolve(ctx, dir), "a cancelled waiter gets nothing") + + close(release) + assert.Equal(t, "https://github.com/acme/web", (<-first).URL) +} + +// A lookup blocked where its context can't reach (a hung network mount) stops being waited for +// after the budget, and the directory gets no second lookup until that one returns. +func TestGitRepositoryResolverGivesUpOnAStuckLookup(t *testing.T) { + dir := t.TempDir() + release := make(chan struct{}) + var calls atomic.Int32 + r := NewGitRepositoryResolver(0) + r.timeout = 20 * time.Millisecond + r.git = func(ctx context.Context, d string, args ...string) (string, error) { + calls.Add(1) + <-release // ignores ctx, like a syscall in the kernel + return (&fakeGit{root: dir, remotes: "origin", url: "https://github.com/acme/web"}).run(ctx, d, args...) + } + + start := time.Now() + repo, definitive := r.Lookup(context.Background(), dir) + assert.Less(t, time.Since(start), 2*time.Second) + assert.Equal(t, GitRepository{}, repo) + assert.False(t, definitive) + + _, definitive = r.Lookup(context.Background(), dir) + assert.False(t, definitive) + assert.Equal(t, int32(1), calls.Load(), "no second lookup while the first is stuck") + + close(release) + assert.Eventually(t, func() bool { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.stuck) == 0 + }, 2*time.Second, 5*time.Millisecond) + r.timeout = time.Second + repo, definitive = r.Lookup(context.Background(), dir) + assert.True(t, definitive) + assert.Equal(t, "https://github.com/acme/web", repo.URL) +} + +// A caller whose context ends stops waiting; the lookup's answer is kept for the next caller. +func TestGitRepositoryResolverCallerGivesUp(t *testing.T) { + dir := t.TempDir() + release := make(chan struct{}) + r := NewGitRepositoryResolver(time.Minute) + r.git = func(ctx context.Context, d string, args ...string) (string, error) { + <-release + return (&fakeGit{root: dir, remotes: "origin", url: "https://github.com/acme/web"}).run(ctx, d, args...) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) + defer cancel() + _, definitive := r.Lookup(ctx, dir) + assert.False(t, definitive) + + // Another caller still gets the answer once the lookup returns. + other := make(chan GitRepository, 1) + go func() { other <- r.Resolve(context.Background(), dir) }() + + close(release) + assert.Equal(t, "https://github.com/acme/web", (<-other).URL) + repo, definitive := r.Lookup(context.Background(), dir) + assert.True(t, definitive) + assert.Equal(t, "https://github.com/acme/web", repo.URL) +} + +// git refusing a repository it doesn't trust, or killed by a signal, says nothing about the +// directory; any other error exit does. +func TestGitExitIsAnswer(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("needs sh") + } + exitOf := func(script string) *exec.ExitError { + _, err := exec.Command("sh", "-c", script).Output() + var exitErr *exec.ExitError + require.ErrorAs(t, err, &exitErr) + return exitErr + } + assert.True(t, gitExitIsAnswer(exitOf(`echo "fatal: not a git repository" >&2; exit 128`))) + assert.True(t, gitExitIsAnswer(exitOf(`echo "error: No such remote 'origin'" >&2; exit 2`))) + assert.False(t, gitExitIsAnswer(exitOf(`echo "fatal: detected dubious ownership in repository at '/x'" >&2; exit 128`))) + assert.False(t, gitExitIsAnswer(exitOf(`kill -9 $$`))) +} + +func TestStatDir(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "f") + require.NoError(t, os.WriteFile(file, nil, 0o600)) + for path, want := range map[string]dirState{dir: dirExists, file: dirMissing, filepath.Join(dir, "missing"): dirMissing} { + assert.Equal(t, want, statDir(path, time.Second), path) + } +} + +func TestGitRepositoryResolverSkipsWhatIsNotADirectory(t *testing.T) { + git := &fakeGit{root: "/x", remotes: "origin", url: "https://github.com/a/b"} + r := NewGitRepositoryResolver(time.Minute) + r.git = git.run + + file := filepath.Join(t.TempDir(), "file") + require.NoError(t, os.WriteFile(file, nil, 0o600)) + for _, dir := range []string{"", "/", "relative/dir", filepath.Join(t.TempDir(), "missing"), file} { + assert.Equal(t, GitRepository{}, r.Resolve(context.Background(), dir), dir) + } + assert.Zero(t, git.calls) +} + +func TestGitRepositoryResolverWithoutRemote(t *testing.T) { + dir := t.TempDir() + git := &fakeGit{root: dir} + r := NewGitRepositoryResolver(0) + r.git = git.run + + assert.Equal(t, GitRepository{Root: dir}, r.Resolve(context.Background(), dir)) + + git.remotes = "origin" + git.url = "/srv/git/local.git" + assert.Equal(t, GitRepository{Root: dir}, r.Resolve(context.Background(), dir), "a local remote is no repository URL") +} + +func TestGitRepositoryResolverWithRealGit(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git is not installed") + } + root := t.TempDir() + run := func(args ...string) { + cmd := exec.Command("git", append([]string{"-C", root}, args...)...) + out, err := cmd.CombinedOutput() + require.NoError(t, err, string(out)) + } + run("init", "-q") + run("remote", "add", "origin", "git@github.com:Acme/Web.git") + sub := filepath.Join(root, "packages", "app") + require.NoError(t, os.MkdirAll(sub, 0o755)) + + resolved, err := filepath.EvalSymlinks(root) + require.NoError(t, err) + + r := NewGitRepositoryResolver(time.Minute) + got := r.Resolve(context.Background(), sub) + assert.Equal(t, "https://github.com/Acme/Web", got.URL) + assert.Equal(t, resolved, got.Root) + + assert.Equal(t, GitRepository{}, r.Resolve(context.Background(), t.TempDir()), "not a work tree") +} diff --git a/model/project_migration.go b/model/project_migration.go new file mode 100644 index 0000000..719f8f8 --- /dev/null +++ b/model/project_migration.go @@ -0,0 +1,170 @@ +package model + +import ( + "context" + "os" + "path/filepath" + "strings" +) + +// ProjectMigrationMarkerFile, in ~/.shelltime, records that the daemon moved this machine's folder +// projects into their repositories' projects, so it does it once. +const ProjectMigrationMarkerFile = "project-repositories.v1" + +// ProjectMigrationMarkerPath is where the daemon's one-time project migration leaves its marker. +func ProjectMigrationMarkerPath() string { + return filepath.Join(os.ExpandEnv("$HOME"), COMMAND_BASE_STORAGE_FOLDER, ProjectMigrationMarkerFile) +} + +// genericHostNames are host names many machines share (a fresh install, a container, a CI +// runner). Another machine's folder project under one of them may exist here as a clone of +// something else, so the migration never claims them. +var genericHostNames = map[string]bool{ + "localhost": true, + "localhost.localdomain": true, + "ubuntu": true, + "debian": true, + "fedora": true, + "archlinux": true, + "raspberrypi": true, + "runner": true, + "buildkitsandbox": true, + "docker-desktop": true, + "(none)": true, +} + +// ProjectMigrationHosts returns the names this machine may have reported its coding agent +// sessions under: its host name, the host name without its domain (macOS adds and drops .local), +// and the machine.name `cc install` wrote into Claude Code's settings, which keeps the name the +// machine had then. Generic names many machines share are left out. +func ProjectMigrationHosts(settingsMachineName string) []string { + var hosts []string + add := func(h string) { + h = strings.TrimSpace(h) + if h == "" || genericHostNames[strings.ToLower(h)] || len(hosts) >= ProjectRepositoriesMaxHosts { + return + } + for _, existing := range hosts { + if existing == h { + return + } + } + hosts = append(hosts, h) + } + hostname, _ := os.Hostname() + add(hostname) + if short, _, ok := strings.Cut(hostname, "."); ok { + add(short) + } + add(settingsMachineName) + return hosts +} + +// projectMigrationMaxPages bounds one migration run: 50 pages of the server's listing (2000 +// folders each). +const projectMigrationMaxPages = 50 + +// projectMigrationMaxUnanswered is how many folders' stats may time out (a hung network mount) +// before a run stops asking about the rest, each of which would cost the whole budget and a +// blocked thread. They count as unchecked, so a later run asks again. Only stats count: git +// refusing a folder, or answering slowly, says nothing about the folders after it. +const projectMigrationMaxUnanswered = 3 + +// ProjectMigrationResult is what a project migration found and did. +type ProjectMigrationResult struct { + // Checked counts the folder projects the server listed for this machine. + Checked int + // Linked lists the folder projects that are clones of a repository with a remote. Without a + // dry run they were moved into their repositories' projects. + Linked []ProjectRepository + // Sessions counts the sessions the server moved. + Sessions int + // Missing counts folders that no longer exist here (renamed, moved or deleted). + Missing int + // NotRepositories counts folders outside a git work tree, or in one without a remote. + NotRepositories int + // Unchecked counts folders git couldn't answer for (it timed out or didn't start); a later + // run asks again. + Unchecked int + // Truncated is true when the server had more folders than this run went through. + Truncated bool +} + +// Complete reports whether every folder of the machine got a definitive answer, so the migration +// needn't run again. +func (r ProjectMigrationResult) Complete() bool { + return !r.Truncated && r.Unchecked == 0 +} + +// MigrateProjectRepositories moves this machine's folder projects into the projects of their git +// repositories: the server lists the folders it still groups sessions by, a page at a time, and +// every folder that still exists here and is a clone with a remote is sent back with its +// repository. Only this machine can answer, since the folders are on its disk. A dry run sends +// nothing back. +func MigrateProjectRepositories(ctx context.Context, endpoint Endpoint, hosts []string, repos *GitRepositoryResolver, dryRun bool) (ProjectMigrationResult, error) { + var result ProjectMigrationResult + if len(hosts) == 0 { + return result, nil + } + + var after *UnresolvedProject + unanswered := 0 + for page := 0; page < projectMigrationMaxPages; page++ { + projects, truncated, err := FetchUnresolvedProjects(ctx, endpoint, hosts, after) + if err != nil { + return result, err + } + result.Checked += len(projects) + result.Truncated = truncated + + var linked []ProjectRepository + for _, p := range projects { + if err := ctx.Err(); err != nil { + return result, err + } + if unanswered >= projectMigrationMaxUnanswered { + result.Unchecked++ + continue + } + switch statDir(p.Pwd, repos.timeout) { + case dirTimedOut: + unanswered++ + result.Unchecked++ + continue + case dirUnknown: + result.Unchecked++ + continue + case dirMissing: + result.Missing++ + continue + } + repo, definitive := repos.Lookup(ctx, p.Pwd) + switch { + case !definitive: + result.Unchecked++ + case repo.URL == "": + result.NotRepositories++ + default: + linked = append(linked, ProjectRepository{Host: p.Host, Pwd: p.Pwd, Repository: repo.URL}) + } + } + result.Linked = append(result.Linked, linked...) + + if !dryRun { + for start := 0; start < len(linked); start += ProjectRepositoriesMaxProjects { + end := min(start+ProjectRepositoriesMaxProjects, len(linked)) + updated, err := SendProjectRepositories(ctx, endpoint, linked[start:end]) + if err != nil { + return result, err + } + result.Sessions += updated + } + } + + if !truncated || len(projects) == 0 { + break + } + after = &projects[len(projects)-1] + } + return result, nil +} diff --git a/model/project_migration_test.go b/model/project_migration_test.go new file mode 100644 index 0000000..2732afa --- /dev/null +++ b/model/project_migration_test.go @@ -0,0 +1,229 @@ +package model + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// projectsServer answers the project repository endpoints and records what it was sent. +type projectsServer struct { + server *httptest.Server + unresolved []UnresolvedProject + // pageSize pages the listing like the server, by the last project sent; 0 sends it whole. + pageSize int + + mu sync.Mutex + hosts []string + afters []*unresolvedProjectCursor + moved [][]ProjectRepository +} + +func newProjectsServer(t *testing.T, unresolved ...UnresolvedProject) *projectsServer { + t.Helper() + ps := &projectsServer{unresolved: unresolved} + ps.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "CLI tok", r.Header.Get("Authorization")) + ps.mu.Lock() + defer ps.mu.Unlock() + switch r.URL.Path { + case "/api/v1/cc/projects/unresolved": + var body unresolvedProjectsRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + ps.hosts = body.Hosts + ps.afters = append(ps.afters, body.After) + start := 0 + if body.After != nil { + for i, p := range ps.unresolved { + if p.Host == body.After.Host && p.Pwd == body.After.Pwd { + start = i + 1 + } + } + } + end := len(ps.unresolved) + if ps.pageSize > 0 { + end = min(start+ps.pageSize, end) + } + _ = json.NewEncoder(w).Encode(unresolvedProjectsResponse{Projects: ps.unresolved[start:end], Truncated: end < len(ps.unresolved)}) + case "/api/v1/cc/projects/repositories": + var body projectRepositoriesRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + ps.moved = append(ps.moved, body.Projects) + _ = json.NewEncoder(w).Encode(projectRepositoriesResponse{Updated: 3 * len(body.Projects)}) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(ps.server.Close) + return ps +} + +func TestMigrateProjectRepositories(t *testing.T) { + clone := t.TempDir() + plain := t.TempDir() + missing := filepath.Join(t.TempDir(), "renamed") + ps := newProjectsServer(t, + UnresolvedProject{Host: "mbp", Pwd: clone, Sessions: 4}, + UnresolvedProject{Host: "mbp.local", Pwd: plain, Sessions: 1}, + UnresolvedProject{Host: "mbp", Pwd: missing, Sessions: 2}, + ) + repos := NewGitRepositoryResolver(time.Minute) + repos.git = func(_ context.Context, dir string, args ...string) (string, error) { + if dir != clone { + return "", gitExitError{errors.New("not a git repository")} + } + return (&fakeGit{root: clone, remotes: "origin", url: "git@github.com:acme/web.git"}).run(context.Background(), dir, args...) + } + endpoint := Endpoint{Token: "tok", APIEndpoint: ps.server.URL} + + result, err := MigrateProjectRepositories(context.Background(), endpoint, []string{"mbp", "mbp.local"}, repos, true) + require.NoError(t, err) + assert.Equal(t, []string{"mbp", "mbp.local"}, ps.hosts) + assert.Equal(t, 3, result.Checked) + assert.Equal(t, []ProjectRepository{{Host: "mbp", Pwd: clone, Repository: "https://github.com/acme/web"}}, result.Linked) + assert.Equal(t, 1, result.Missing) + assert.Equal(t, 1, result.NotRepositories) + assert.Empty(t, ps.moved, "a dry run changes nothing") + + result, err = MigrateProjectRepositories(context.Background(), endpoint, []string{"mbp"}, repos, false) + require.NoError(t, err) + require.Len(t, ps.moved, 1) + assert.Equal(t, result.Linked, ps.moved[0]) + assert.Equal(t, 3, result.Sessions) + assert.True(t, result.Complete()) +} + +// The listing comes a page at a time; folders that can't be moved stay in it, so the run pages +// by the last project of each page. +func TestMigrateProjectRepositoriesPages(t *testing.T) { + ps := newProjectsServer(t, + UnresolvedProject{Host: "mbp", Pwd: "/gone/a"}, + UnresolvedProject{Host: "mbp", Pwd: "/gone/b"}, + UnresolvedProject{Host: "mbp", Pwd: "/gone/c"}, + ) + ps.pageSize = 2 + result, err := MigrateProjectRepositories(context.Background(), Endpoint{Token: "tok", APIEndpoint: ps.server.URL}, []string{"mbp"}, NewGitRepositoryResolver(0), false) + require.NoError(t, err) + assert.Equal(t, 3, result.Checked) + assert.Equal(t, 3, result.Missing) + assert.True(t, result.Complete()) + require.Len(t, ps.afters, 2) + assert.Nil(t, ps.afters[0]) + assert.Equal(t, &unresolvedProjectCursor{Host: "mbp", Pwd: "/gone/b"}, ps.afters[1]) +} + +// A folder git couldn't answer for is unknown, not "no repository": the run isn't complete. +func TestMigrateProjectRepositoriesCountsUncheckedFolders(t *testing.T) { + dir := t.TempDir() + ps := newProjectsServer(t, UnresolvedProject{Host: "mbp", Pwd: dir}) + repos := NewGitRepositoryResolver(time.Minute) + repos.git = func(context.Context, string, ...string) (string, error) { + return "", context.DeadlineExceeded + } + result, err := MigrateProjectRepositories(context.Background(), Endpoint{Token: "tok", APIEndpoint: ps.server.URL}, []string{"mbp"}, repos, false) + require.NoError(t, err) + assert.Equal(t, 1, result.Unchecked) + assert.Zero(t, result.NotRepositories) + assert.False(t, result.Complete()) + assert.Empty(t, ps.moved) +} + +// After a few folders' stats time out (a hung mount), a run stops asking about the rest; git +// refusing folders doesn't stop it. +func TestMigrateProjectRepositoriesStopsAskingWhenUnanswered(t *testing.T) { + var projects []UnresolvedProject + for range 6 { + projects = append(projects, UnresolvedProject{Host: "mbp", Pwd: t.TempDir()}) + } + ps := newProjectsServer(t, projects...) + endpoint := Endpoint{Token: "tok", APIEndpoint: ps.server.URL} + + var mu sync.Mutex + asked := map[string]bool{} + repos := NewGitRepositoryResolver(0) + repos.git = func(_ context.Context, dir string, _ ...string) (string, error) { + mu.Lock() + asked[dir] = true + mu.Unlock() + return "", context.DeadlineExceeded // or a safe.directory refusal: no answer + } + result, err := MigrateProjectRepositories(context.Background(), endpoint, []string{"mbp"}, repos, false) + require.NoError(t, err) + assert.Equal(t, 6, result.Unchecked) + assert.Len(t, asked, 6, "folders git didn't answer for don't stop the run") + + original := statDir + t.Cleanup(func() { statDir = original }) + var stats int + statDir = func(string, time.Duration) dirState { + stats++ + return dirTimedOut + } + result, err = MigrateProjectRepositories(context.Background(), endpoint, []string{"mbp"}, repos, false) + require.NoError(t, err) + assert.Equal(t, 6, result.Unchecked) + assert.False(t, result.Complete()) + assert.Equal(t, projectMigrationMaxUnanswered, stats, "after a few hung stats the rest aren't asked about") +} + +func TestMigrateProjectRepositoriesWithoutHosts(t *testing.T) { + result, err := MigrateProjectRepositories(context.Background(), Endpoint{Token: "tok", APIEndpoint: "http://127.0.0.1:0"}, nil, NewGitRepositoryResolver(0), false) + require.NoError(t, err, "no names to ask about means nothing to do, and no request") + assert.Zero(t, result.Checked) +} + +func TestMigrateProjectRepositoriesReportsServerErrors(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"not found"}`)) + })) + t.Cleanup(server.Close) + + _, err := MigrateProjectRepositories(context.Background(), Endpoint{Token: "tok", APIEndpoint: server.URL}, []string{"mbp"}, NewGitRepositoryResolver(0), false) + var statusErr *HTTPStatusError + require.ErrorAs(t, err, &statusErr) + assert.Equal(t, http.StatusNotFound, statusErr.StatusCode) +} + +func TestProjectMigrationHosts(t *testing.T) { + hostname, err := os.Hostname() + require.NoError(t, err) + if genericHostNames[strings.ToLower(hostname)] { + t.Skip("this machine's host name is a generic one") + } + hosts := ProjectMigrationHosts("old-name") + assert.Equal(t, hostname, hosts[0]) + assert.Equal(t, "old-name", hosts[len(hosts)-1]) + if short, _, ok := strings.Cut(hostname, "."); ok { + assert.Contains(t, hosts, short) + } + assert.Equal(t, hosts[:len(hosts)-1], ProjectMigrationHosts(hostname), "names are listed once") + assert.NotContains(t, ProjectMigrationHosts("localhost"), "localhost", "a name many machines share is left out") + assert.NotContains(t, ProjectMigrationHosts("Ubuntu"), "Ubuntu") +} + +func TestResourceMachineName(t *testing.T) { + dir := t.TempDir() + s := &ClaudeSettingsAICodeOtelEnvService{settingsPath: filepath.Join(dir, "settings.json")} + assert.Empty(t, s.ResourceMachineName(), "no settings file") + + require.NoError(t, os.WriteFile(s.settingsPath, []byte(`{"env":{"OTEL_RESOURCE_ATTRIBUTES":"user.name=me, machine.name=old-mbp ,team.id=shelltime"}}`), 0o600)) + assert.Equal(t, "old-mbp", s.ResourceMachineName()) + + require.NoError(t, os.WriteFile(s.settingsPath, []byte(`{"env":{}}`), 0o600)) + assert.Empty(t, s.ResourceMachineName()) + + require.NoError(t, os.WriteFile(s.settingsPath, []byte(`not json`), 0o600)) + assert.Empty(t, s.ResourceMachineName()) +} diff --git a/model/types.go b/model/types.go index 1c3e0ab..0797411 100644 --- a/model/types.go +++ b/model/types.go @@ -32,6 +32,17 @@ type AICodeOtel struct { Enabled *bool `toml:"enabled" yaml:"enabled" json:"enabled"` GRPCPort int `toml:"grpcPort,omitempty" yaml:"grpcPort,omitempty" json:"grpcPort,omitempty"` // default: 54027 Debug *bool `toml:"debug" yaml:"debug" json:"debug"` // write raw JSON to debug files + // SendRepository names the git repository of each coding agent session's folder, so the + // server groups sessions by repository (default true). False: ShellTime never asks git or + // sends a repository, and the daemon removes the one Claude Code reports, so sessions are + // grouped by machine and folder. + SendRepository *bool `toml:"sendRepository,omitempty" yaml:"sendRepository,omitempty" json:"sendRepository,omitempty"` +} + +// SendsRepository reports whether AI coding agent data may name its git repository: on unless +// aiCodeOtel.sendRepository is false. +func (c ShellTimeConfig) SendsRepository() bool { + return c.AICodeOtel == nil || c.AICodeOtel.SendRepository == nil || *c.AICodeOtel.SendRepository } // CodeTracking configuration for coding activity heartbeat tracking