From 5f7fc0fbc9890569d8da876ac32dfe84182129e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:52:43 +0000 Subject: [PATCH 01/11] feat(daemon): send the git repository so projects group by repository The server grouped coding agent sessions into projects by working directory, so renaming or moving a clone started a new project. The CLI now names the git repository a session ran in, as vcs.repository.url.full in the form Claude Code reports (https:///, credentials and .git dropped). - model.GitRepositoryResolver asks git for a directory's origin remote (else upstream, else the first) without optional locks, and caches answers, negative ones too. - The OTEL processor adds the repository to records whose resource has a pwd and that don't name one; Claude Code's own value wins. - session_project sends the statusline directory's repository. - Backfill adds it to uploaded events: the repository a Codex rollout recorded at the start, else the transcript directory's. - Migration: `shelltime cc projects` (also `codex projects`) lists this machine's folder projects from the server and moves the folders that are still clones into their repositories' projects. The daemon runs it once, two minutes after start, and leaves a marker in ~/.shelltime; an older server or a failure leaves none, so the next start tries again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- CLAUDE.md | 2 + cmd/daemon/main.go | 3 + commands/aicode_backfill.go | 3 + commands/aicode_projects.go | 86 +++++++++++ commands/aicode_projects_test.go | 66 ++++++++ commands/cc.go | 1 + commands/codex.go | 1 + daemon/aicode_otel_processor.go | 37 +++++ daemon/aicode_otel_repository_test.go | 81 ++++++++++ daemon/project_migration.go | 80 ++++++++++ daemon/project_migration_test.go | 69 +++++++++ daemon/socket.go | 20 ++- daemon/socket_extra_test.go | 27 ++++ model/aicode_backfill_codex.go | 9 ++ model/aicode_backfill_codex_test.go | 4 +- model/aicode_backfill_common.go | 29 ++++ model/aicode_backfill_common_test.go | 31 ++++ model/aicode_backfill_types.go | 4 + model/aicode_otel_claude_settings.go | 25 +++ model/api_project_repositories.go | 83 ++++++++++ model/api_senders_test.go | 5 +- model/api_session_project.go | 9 +- model/git_repository.go | 215 ++++++++++++++++++++++++++ model/git_repository_test.go | 181 ++++++++++++++++++++++ model/project_migration.go | 101 ++++++++++++ model/project_migration_test.go | 127 +++++++++++++++ 26 files changed, 1293 insertions(+), 6 deletions(-) create mode 100644 commands/aicode_projects.go create mode 100644 commands/aicode_projects_test.go create mode 100644 daemon/aicode_otel_repository_test.go create mode 100644 daemon/project_migration.go create mode 100644 daemon/project_migration_test.go create mode 100644 model/api_project_repositories.go create mode 100644 model/git_repository.go create mode 100644 model/git_repository_test.go create mode 100644 model/project_migration.go create mode 100644 model/project_migration_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 46c7760..0c34b8f 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 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, and caches answers, negative ones too (10 min in the daemon). `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 records whose resource has a `pwd` and that don't name one (Claude Code's own value wins), 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) +- **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 (marker `~/.shelltime/project-repositories.v1`; a 404 from an older server or a failure 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`) from `POST /api/v1/cc/projects/unresolved` 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) - **HeartbeatResyncService**: Periodic resync of failed heartbeats (30-min interval) - **CleanupTimerService**: Periodic log file cleanup (24-hour interval) diff --git a/cmd/daemon/main.go b/cmd/daemon/main.go index cf7f34e..1ce4567 100644 --- a/cmd/daemon/main.go +++ b/cmd/daemon/main.go @@ -199,6 +199,9 @@ func main() { // (statusline mods, the desktop app, idle sessions). processor.StartAnthropicUsageSync() + // Group the sessions recorded before repositories were named by repository, not folder. + 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..5ea44f9 100644 --- a/commands/aicode_backfill.go +++ b/commands/aicode_backfill.go @@ -150,6 +150,9 @@ func runAICodeBackfill(c *cli.Context, src aiCodeBackfillSource) error { return nil } + // The server groups sessions into projects by git repository when it knows it. + 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..50c884b --- /dev/null +++ b/commands/aicode_projects.go @@ -0,0 +1,86 @@ +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, +} + +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") + } + endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint} + hosts := model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) + 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) + 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..ed0ad04 --- /dev/null +++ b/commands/aicode_projects_test.go @@ -0,0 +1,66 @@ +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 }) + + 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 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..09e1704 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -40,6 +40,9 @@ 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 // maxRequestBytes bounds the JSON body of one backend request; larger batches are split. maxRequestBytes int @@ -65,10 +68,37 @@ func NewAICodeOtelProcessor(config model.ShellTimeConfig) *AICodeOtelProcessor { hostname: hostname, debug: debug, cloudSessionID: model.CloudSessionIDFromEnv(os.Getenv), + repos: model.NewGitRepositoryResolver(repositoryCacheTTL), 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 "". +func (p *AICodeOtelProcessor) resolveRepository(ctx context.Context, res *otelResource) string { + if p.repos == nil || res.attrs.Pwd == "" { + return "" + } + return p.repos.Resolve(ctx, res.attrs.Pwd).URL +} + +// fillRepository adds the resource's repository to a record that doesn't name one yet. It is +// seeded before the record's own attributes, so a vcs.repository.url.full that Claude Code +// sent on the record still wins. +func fillRepository(attrs map[string]any, res *otelResource) map[string]any { + if res.repository == "" { + return attrs + } + if _, ok := attrs[model.AICodeRepositoryAttribute]; ok { + return attrs + } + return setAttribute(attrs, model.AICodeRepositoryAttribute, res.repository) +} + // 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 +147,9 @@ 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 } // deterministicMarshal encodes OTLP messages byte-for-byte reproducibly, so an exporter retry of @@ -185,6 +218,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 +265,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 @@ -671,6 +706,7 @@ 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) + metric.Attributes = fillRepository(metric.Attributes, res) // Then extract data point attributes (can override resource attrs) for _, attr := range dp.GetAttributes() { applyMetricAttribute(&metric, attr, metricType) @@ -761,6 +797,7 @@ 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) + event.Attributes = fillRepository(event.Attributes, res) var fallbacks eventFallbacks for _, attr := range lr.GetAttributes() { diff --git a/daemon/aicode_otel_repository_test.go b/daemon/aicode_otel_repository_test.go new file mode 100644 index 0000000..abed260 --- /dev/null +++ b/daemon/aicode_otel_repository_test.go @@ -0,0 +1,81 @@ +package daemon + +import ( + "context" + "os/exec" + "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) + 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]) +} + +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") +} diff --git a/daemon/project_migration.go b/daemon/project_migration.go new file mode 100644 index 0000000..5cd64f8 --- /dev/null +++ b/daemon/project_migration.go @@ -0,0 +1,80 @@ +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, or a failure, +// 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()) +} + +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 == "" { + 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 := model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) + 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 + } + + marker, _ := json.Marshal(projectMigrationMarker{ + MigratedAt: time.Now().UTC(), + Checked: result.Checked, + Linked: len(result.Linked), + Sessions: result.Sessions, + }) + if err := os.MkdirAll(filepath.Dir(markerPath), 0o700); err == nil { + err = os.WriteFile(markerPath, marker, 0o600) + } + if err != nil { + slog.Warn("Failed to write the project migration marker", slog.Any("err", err)) + } + 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)) +} diff --git a/daemon/project_migration_test.go b/daemon/project_migration_test.go new file mode 100644 index 0000000..93e4546 --- /dev/null +++ b/daemon/project_migration_test.go @@ -0,0 +1,69 @@ +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" +) + +func TestRunProjectMigrationOnce(t *testing.T) { + 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") +} + +func TestRunProjectMigrationOnceRetriesLater(t *testing.T) { + 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..8215e49 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,6 +127,7 @@ func NewSocketHandler(config *model.ShellTimeConfig, ch *GoChannel) *SocketHandl stopChan: make(chan struct{}), ccInfoTimer: NewCCInfoTimerService(config), aiCloudOnly: model.IsAICloudOnly(*config, os.Getenv), + repos: model.NewGitRepositoryResolver(repositoryCacheTTL), } } @@ -308,7 +312,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 +323,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..0221de6 --- /dev/null +++ b/model/api_project_repositories.go @@ -0,0 +1,83 @@ +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"` +} + +type unresolvedProjectsResponse struct { + Projects []UnresolvedProject `json:"projects"` +} + +type projectRepositoriesRequest struct { + Projects []ProjectRepository `json:"projects"` +} + +type projectRepositoriesResponse struct { + Updated int `json:"updated"` +} + +// FetchUnresolvedProjects lists the folder projects of the given hosts, the names this machine +// has reported its sessions under. +func FetchUnresolvedProjects(ctx context.Context, endpoint Endpoint, hosts []string) ([]UnresolvedProject, error) { + ctx, span := modelTracer.Start(ctx, "project_repositories.unresolved") + defer span.End() + + var resp unresolvedProjectsResponse + err := SendHTTPRequestJSON(HTTPRequestOptions[*unresolvedProjectsRequest, unresolvedProjectsResponse]{ + Context: ctx, + Endpoint: endpoint, + Method: http.MethodPost, + Path: "/api/v1/cc/projects/unresolved", + Payload: &unresolvedProjectsRequest{Hosts: hosts}, + Response: &resp, + Timeout: 30 * time.Second, + }) + return resp.Projects, 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/git_repository.go b/model/git_repository.go new file mode 100644 index 0000000..9e4532c --- /dev/null +++ b/model/git_repository.go @@ -0,0 +1,215 @@ +package model + +import ( + "context" + "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:] + } + + 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 + } + 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 = 2 * time.Second + gitRepositoryMaxEntries = 512 +) + +// GitRepositoryResolver finds the repository a directory belongs to with the git CLI, and +// remembers the answer for a while, negative ones included: the daemon asks for the same few +// directories on every OTEL export and statusline render. +type GitRepositoryResolver struct { + ttl 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 +} + +type gitRepositoryEntry struct { + repo GitRepository + expires time.Time +} + +// NewGitRepositoryResolver returns a resolver that keeps answers for ttl (0 keeps nothing). +func NewGitRepositoryResolver(ttl time.Duration) *GitRepositoryResolver { + return &GitRepositoryResolver{ + ttl: ttl, + git: runGit, + now: time.Now, + cache: make(map[string]gitRepositoryEntry), + } +} + +// runGit runs git without taking optional locks (it must never get in the way of the user's +// own git commands), without prompting and under a deadline. +func runGit(ctx context.Context, dir string, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(ctx, gitRepositoryTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, "git", append([]string{"-C", dir}, args...)...) + cmd.Env = append(os.Environ(), "GIT_OPTIONAL_LOCKS=0", "GIT_TERMINAL_PROMPT=0") + out, err := cmd.Output() + return strings.TrimSpace(string(out)), err +} + +// 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 { + dir = strings.TrimSpace(dir) + if dir == "" || !filepath.IsAbs(dir) { + return GitRepository{} + } + dir = filepath.Clean(dir) + if dir == string(filepath.Separator) { + return GitRepository{} + } + + now := r.now() + r.mu.Lock() + if e, ok := r.cache[dir]; ok && now.Before(e.expires) { + r.mu.Unlock() + return e.repo + } + r.mu.Unlock() + + repo := r.lookup(ctx, dir) + if ctx.Err() != nil { + return repo // a cancelled lookup says nothing about the directory + } + + if r.ttl > 0 { + r.mu.Lock() + 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, expires: now.Add(r.ttl)} + r.mu.Unlock() + } + return repo +} + +func (r *GitRepositoryResolver) lookup(ctx context.Context, dir string) GitRepository { + if info, err := os.Stat(dir); err != nil || !info.IsDir() { + return GitRepository{} + } + root, err := r.git(ctx, dir, "rev-parse", "--show-toplevel") + if err != nil || root == "" { + return GitRepository{} + } + repo := GitRepository{Root: filepath.Clean(root)} + + remotes, err := r.git(ctx, dir, "remote") + if err != nil { + return repo + } + name := pickGitRemote(strings.Fields(remotes)) + if name == "" { + return repo + } + // 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 + } + if u, ok := CanonicalRepositoryURL(raw); ok { + repo.URL = u + } + return repo +} + +// 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..8230f57 --- /dev/null +++ b/model/git_repository_test.go @@ -0,0 +1,181 @@ +package model + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "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) + }) + } +} + +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 "", 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) +} + +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..08ce5bb --- /dev/null +++ b/model/project_migration.go @@ -0,0 +1,101 @@ +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) +} + +// 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. +func ProjectMigrationHosts(settingsMachineName string) []string { + var hosts []string + add := func(h string) { + h = strings.TrimSpace(h) + if 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 +} + +// 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 +} + +// MigrateProjectRepositories moves this machine's folder projects into the projects of their git +// repositories: the server lists the folders it still groups sessions by, 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 + projects, err := FetchUnresolvedProjects(ctx, endpoint, hosts) + if err != nil { + return result, err + } + result.Checked = len(projects) + + for _, p := range projects { + if err := ctx.Err(); err != nil { + return result, err + } + if info, err := os.Stat(p.Pwd); err != nil || !info.IsDir() { + result.Missing++ + continue + } + repo := repos.Resolve(ctx, p.Pwd) + if repo.URL == "" { + result.NotRepositories++ + continue + } + result.Linked = append(result.Linked, ProjectRepository{Host: p.Host, Pwd: p.Pwd, Repository: repo.URL}) + } + if dryRun { + return result, nil + } + + for start := 0; start < len(result.Linked); start += ProjectRepositoriesMaxProjects { + end := min(start+ProjectRepositoriesMaxProjects, len(result.Linked)) + updated, err := SendProjectRepositories(ctx, endpoint, result.Linked[start:end]) + if err != nil { + return result, err + } + result.Sessions += updated + } + return result, nil +} diff --git a/model/project_migration_test.go b/model/project_migration_test.go new file mode 100644 index 0000000..674084e --- /dev/null +++ b/model/project_migration_test.go @@ -0,0 +1,127 @@ +package model + +import ( + "context" + "encoding/json" + "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 + + mu sync.Mutex + hosts []string + 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 + _ = json.NewEncoder(w).Encode(unresolvedProjectsResponse{Projects: 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 "", os.ErrNotExist + } + 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) +} + +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) + 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") +} + +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()) +} From 81850e6ca1e6dc74ca2ae45fd088d1146541d4b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:51:45 +0000 Subject: [PATCH 02/11] fix(daemon): bound and dedupe git lookups, keep migration to this machine Review follow-ups on the git repository resolver and project migration: - A lookup runs within one 2 s budget instead of 2 s per git call, and concurrent lookups of one directory share one run, since the daemon resolves on the OTLP export path. git is found through CommandService, so the daemon's limited PATH reaches Homebrew and /usr/local/bin. - Only definitive answers are cached. A timeout or git failing to start no longer hides a directory's repository for the whole TTL. - The migration skips host names many machines share (localhost, ubuntu, runner, ...), leaves no marker when the server cut its list short, logs a marker it couldn't write, and doesn't run in AI cloud only mode. - README documents `shelltime cc projects` / `shelltime codex projects`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- CLAUDE.md | 4 +- README.md | 8 +++ cmd/daemon/main.go | 5 +- commands/aicode_projects.go | 6 ++ daemon/project_migration.go | 33 +++++---- daemon/project_migration_test.go | 26 +++++++ model/api_project_repositories.go | 11 +-- model/git_repository.go | 116 ++++++++++++++++++++++-------- model/git_repository_test.go | 82 ++++++++++++++++++++- model/project_migration.go | 30 +++++++- model/project_migration_test.go | 17 ++++- 11 files changed, 283 insertions(+), 55 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 0c34b8f..04bb403 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,8 +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 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, and caches answers, negative ones too (10 min in the daemon). `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 records whose resource has a `pwd` and that don't name one (Claude Code's own value wins), 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) -- **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 (marker `~/.shelltime/project-repositories.v1`; a 404 from an older server or a failure 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`) from `POST /api/v1/cc/projects/unresolved` 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) +- **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. It caches definitive answers, negative ones too (10 min in the daemon), never a timeout or git failing to start. `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 records whose resource has a `pwd` and that don't name one (Claude Code's own value wins), 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) +- **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`; a 404 from an older server, a failure or a list the server marked `truncated` 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` 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) - **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..521d116 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,12 @@ 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 host names many machines share, like `localhost`, are skipped. + ## Codex Usage Tracking ShellTime receives Codex data through two independent paths: diff --git a/cmd/daemon/main.go b/cmd/daemon/main.go index 1ce4567..1d748b2 100644 --- a/cmd/daemon/main.go +++ b/cmd/daemon/main.go @@ -200,7 +200,10 @@ func main() { processor.StartAnthropicUsageSync() // Group the sessions recorded before repositories were named by repository, not folder. - go daemon.RunProjectMigrationOnce(ctx, cfg) + // 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) diff --git a/commands/aicode_projects.go b/commands/aicode_projects.go index 50c884b..cd89eeb 100644 --- a/commands/aicode_projects.go +++ b/commands/aicode_projects.go @@ -61,6 +61,9 @@ func commandAICodeProjects(c *cli.Context) error { return fmt.Errorf("project migration failed: %w", err) } + 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") + } if result.Checked == 0 { color.Green.Println("Every project of this machine is already grouped by repository.") return nil @@ -76,6 +79,9 @@ func commandAICodeProjects(c *cli.Context) error { 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.Truncated { + color.Yellow.Println("The server listed only part of this machine's folder projects; run it again to check the rest.") + } switch { case dryRun: color.Green.Println("Dry run: nothing was changed.") diff --git a/daemon/project_migration.go b/daemon/project_migration.go index 5cd64f8..55de2ee 100644 --- a/daemon/project_migration.go +++ b/daemon/project_migration.go @@ -20,8 +20,9 @@ const projectMigrationDelay = 2 * time.Minute // 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, or a failure, -// leaves none, so the next start tries again. `shelltime cc projects` runs it by hand. +// and leaves a marker when it is done; a server that doesn't support it yet, a failure, or a +// list the server cut short 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()) } @@ -59,22 +60,26 @@ func runProjectMigrationOnce(ctx context.Context, cfg model.ShellTimeConfig, del return } - marker, _ := json.Marshal(projectMigrationMarker{ - MigratedAt: time.Now().UTC(), - Checked: result.Checked, - Linked: len(result.Linked), - Sessions: result.Sessions, - }) - if err := os.MkdirAll(filepath.Dir(markerPath), 0o700); err == nil { - err = os.WriteFile(markerPath, marker, 0o600) - } - if err != nil { - slog.Warn("Failed to write the project migration marker", slog.Any("err", err)) + if !result.Truncated { + 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("notRepositories", result.NotRepositories), + slog.Bool("truncated", result.Truncated)) } diff --git a/daemon/project_migration_test.go b/daemon/project_migration_test.go index 93e4546..884a5d3 100644 --- a/daemon/project_migration_test.go +++ b/daemon/project_migration_test.go @@ -49,6 +49,32 @@ func TestRunProjectMigrationOnce(t *testing.T) { assert.Equal(t, int32(2), requests.Load(), "with the marker in place nothing is asked again") } +func TestRunProjectMigrationOnceRetriesATruncatedList(t *testing.T) { + 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) { + 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) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) diff --git a/model/api_project_repositories.go b/model/api_project_repositories.go index 0221de6..e7130bb 100644 --- a/model/api_project_repositories.go +++ b/model/api_project_repositories.go @@ -34,6 +34,8 @@ type unresolvedProjectsRequest struct { type unresolvedProjectsResponse struct { Projects []UnresolvedProject `json:"projects"` + // Truncated is true when the server matched more folders than it listed. + Truncated bool `json:"truncated"` } type projectRepositoriesRequest struct { @@ -45,13 +47,14 @@ type projectRepositoriesResponse struct { } // FetchUnresolvedProjects lists the folder projects of the given hosts, the names this machine -// has reported its sessions under. -func FetchUnresolvedProjects(ctx context.Context, endpoint Endpoint, hosts []string) ([]UnresolvedProject, error) { +// has reported its sessions under. truncated is true when the server matched more than it +// listed. +func FetchUnresolvedProjects(ctx context.Context, endpoint Endpoint, hosts []string) (projects []UnresolvedProject, truncated bool, err error) { ctx, span := modelTracer.Start(ctx, "project_repositories.unresolved") defer span.End() var resp unresolvedProjectsResponse - err := SendHTTPRequestJSON(HTTPRequestOptions[*unresolvedProjectsRequest, unresolvedProjectsResponse]{ + err = SendHTTPRequestJSON(HTTPRequestOptions[*unresolvedProjectsRequest, unresolvedProjectsResponse]{ Context: ctx, Endpoint: endpoint, Method: http.MethodPost, @@ -60,7 +63,7 @@ func FetchUnresolvedProjects(ctx context.Context, endpoint Endpoint, hosts []str Response: &resp, Timeout: 30 * time.Second, }) - return resp.Projects, err + return resp.Projects, resp.Truncated, err } // SendProjectRepositories moves folder projects into their repositories' projects and returns diff --git a/model/git_repository.go b/model/git_repository.go index 9e4532c..1ea067c 100644 --- a/model/git_repository.go +++ b/model/git_repository.go @@ -2,6 +2,7 @@ package model import ( "context" + "errors" "net/url" "os" "os/exec" @@ -85,21 +86,33 @@ type GitRepository struct { } 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 gitRepositoryMaxEntries = 512 ) +// gitExitError is git exiting with an error status: a definitive answer (not a work tree, no +// such remote), unlike a timeout or git failing to start, 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 the answer for a while, negative ones included: the daemon asks for the same few -// directories on every OTEL export and statusline render. +// remembers definitive answers for a while, negative ones included: the daemon asks for the same +// few directories on every OTEL export and statusline render. Concurrent lookups of one +// directory share one run of git. type GitRepositoryResolver struct { ttl 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 + mu sync.Mutex + cache map[string]gitRepositoryEntry + inflight map[string]*gitRepositoryCall } type gitRepositoryEntry struct { @@ -107,24 +120,48 @@ type gitRepositoryEntry struct { expires time.Time } +type gitRepositoryCall struct { + done chan struct{} + repo GitRepository +} + // NewGitRepositoryResolver returns a resolver that keeps answers for ttl (0 keeps nothing). func NewGitRepositoryResolver(ttl time.Duration) *GitRepositoryResolver { return &GitRepositoryResolver{ - ttl: ttl, - git: runGit, - now: time.Now, - cache: make(map[string]gitRepositoryEntry), + ttl: ttl, + git: runGit, + now: time.Now, + cache: make(map[string]gitRepositoryEntry), + inflight: make(map[string]*gitRepositoryCall), } } +var ( + gitBinaryOnce sync.Once + gitBinary = "git" +) + +// gitExecutable finds git once, also where the daemon's limited PATH doesn't reach (Homebrew, +// /usr/local/bin), through the CommandService's fallback paths. +func gitExecutable() string { + gitBinaryOnce.Do(func() { + if path, err := NewCommandService().LookPath("git"); err == nil { + gitBinary = path + } + }) + return gitBinary +} + // runGit runs git without taking optional locks (it must never get in the way of the user's -// own git commands), without prompting and under a deadline. +// own git commands) and without prompting, under ctx's deadline. func runGit(ctx context.Context, dir string, args ...string) (string, error) { - ctx, cancel := context.WithTimeout(ctx, gitRepositoryTimeout) - defer cancel() - cmd := exec.CommandContext(ctx, "git", append([]string{"-C", dir}, args...)...) + cmd := exec.CommandContext(ctx, gitExecutable(), append([]string{"-C", dir}, args...)...) cmd.Env = append(os.Environ(), "GIT_OPTIONAL_LOCKS=0", "GIT_TERMINAL_PROMPT=0") out, err := cmd.Output() + var exitErr *exec.ExitError + if err != nil && errors.As(err, &exitErr) && ctx.Err() == nil { + return "", gitExitError{err} + } return strings.TrimSpace(string(out)), err } @@ -140,21 +177,35 @@ func (r *GitRepositoryResolver) Resolve(ctx context.Context, dir string) GitRepo return GitRepository{} } - now := r.now() r.mu.Lock() - if e, ok := r.cache[dir]; ok && now.Before(e.expires) { + if e, ok := r.cache[dir]; ok && r.now().Before(e.expires) { r.mu.Unlock() return e.repo } + if call, ok := r.inflight[dir]; ok { + r.mu.Unlock() + select { + case <-call.done: + return call.repo + case <-ctx.Done(): + return GitRepository{} + } + } + call := &gitRepositoryCall{done: make(chan struct{})} + r.inflight[dir] = call r.mu.Unlock() - repo := r.lookup(ctx, dir) - if ctx.Err() != nil { - return repo // a cancelled lookup says nothing about the directory - } + // The lookup isn't tied to this caller's context, so a caller that gives up doesn't spoil + // the answer for the others waiting on it; the budget bounds it instead. + lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), gitRepositoryTimeout) + repo, definitive := r.lookup(lookupCtx, dir) + cancel() - if r.ttl > 0 { - r.mu.Lock() + r.mu.Lock() + call.repo = repo + delete(r.inflight, dir) + if definitive && r.ttl > 0 { + now := r.now() if len(r.cache) >= gitRepositoryMaxEntries { for k, e := range r.cache { if !now.Before(e.expires) { @@ -166,38 +217,45 @@ func (r *GitRepositoryResolver) Resolve(ctx context.Context, dir string) GitRepo } } r.cache[dir] = gitRepositoryEntry{repo: repo, expires: now.Add(r.ttl)} - r.mu.Unlock() } + r.mu.Unlock() + close(call.done) return repo } -func (r *GitRepositoryResolver) lookup(ctx context.Context, dir string) GitRepository { +// 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{} + return GitRepository{}, true } root, err := r.git(ctx, dir, "rev-parse", "--show-toplevel") if err != nil || root == "" { - return GitRepository{} + return GitRepository{}, err == nil || answered(err) } - repo := GitRepository{Root: filepath.Clean(root)} + repo = GitRepository{Root: filepath.Clean(root)} remotes, err := r.git(ctx, dir, "remote") if err != nil { - return repo + return repo, answered(err) } name := pickGitRemote(strings.Fields(remotes)) if name == "" { - return repo + 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 + return repo, answered(err) } if u, ok := CanonicalRepositoryURL(raw); ok { repo.URL = u } - return repo + return repo, true } // pickGitRemote prefers origin, the remote a clone creates and the one the user pushes to (so a diff --git a/model/git_repository_test.go b/model/git_repository_test.go index 8230f57..c9222cf 100644 --- a/model/git_repository_test.go +++ b/model/git_repository_test.go @@ -6,6 +6,7 @@ import ( "os" "os/exec" "path/filepath" + "sync" "testing" "time" @@ -85,7 +86,7 @@ func (f *fakeGit) run(_ context.Context, dir string, args ...string) (string, er switch { case args[0] == "rev-parse": if f.root == "" { - return "", errors.New("not a git repository") + return "", gitExitError{errors.New("not a git repository")} } return f.root, nil case len(args) == 1 && args[0] == "remote": @@ -128,6 +129,85 @@ func TestGitRepositoryResolverCachesNegativeAnswers(t *testing.T) { assert.Equal(t, 1, git.calls) } +// A timeout, or git failing to start, says nothing about the directory: the next lookup asks +// again instead of serving a cached "no repository" for the whole TTL. +func TestGitRepositoryResolverDoesNotCacheTransientFailures(t *testing.T) { + dir := t.TempDir() + calls := 0 + failing := true + r := NewGitRepositoryResolver(time.Minute) + 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...) + } + + assert.Equal(t, GitRepository{}, r.Resolve(context.Background(), dir)) + failing = false + assert.Equal(t, "https://github.com/acme/web", r.Resolve(context.Background(), dir).URL) + assert.Equal(t, 4, calls, "the failed lookup was not cached") + r.Resolve(context.Background(), dir) + assert.Equal(t, 4, calls, "the answer was") +} + +// 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) +} + func TestGitRepositoryResolverSkipsWhatIsNotADirectory(t *testing.T) { git := &fakeGit{root: "/x", remotes: "origin", url: "https://github.com/a/b"} r := NewGitRepositoryResolver(time.Minute) diff --git a/model/project_migration.go b/model/project_migration.go index 08ce5bb..07af211 100644 --- a/model/project_migration.go +++ b/model/project_migration.go @@ -16,15 +16,32 @@ 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. +// 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 == "" || len(hosts) >= ProjectRepositoriesMaxHosts { + if h == "" || genericHostNames[strings.ToLower(h)] || len(hosts) >= ProjectRepositoriesMaxHosts { return } for _, existing := range hosts { @@ -56,6 +73,9 @@ type ProjectMigrationResult struct { Missing int // NotRepositories counts folders outside a git work tree, or in one without a remote. NotRepositories int + // Truncated is true when the server matched more folders than it listed; a later run sees + // the rest, once the folders this one moved are gone from the list. + Truncated bool } // MigrateProjectRepositories moves this machine's folder projects into the projects of their git @@ -64,11 +84,15 @@ type ProjectMigrationResult struct { // 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 - projects, err := FetchUnresolvedProjects(ctx, endpoint, hosts) + if len(hosts) == 0 { + return result, nil + } + projects, truncated, err := FetchUnresolvedProjects(ctx, endpoint, hosts) if err != nil { return result, err } result.Checked = len(projects) + result.Truncated = truncated for _, p := range projects { if err := ctx.Err(); err != nil { diff --git a/model/project_migration_test.go b/model/project_migration_test.go index 674084e..0f5804a 100644 --- a/model/project_migration_test.go +++ b/model/project_migration_test.go @@ -20,6 +20,7 @@ import ( type projectsServer struct { server *httptest.Server unresolved []UnresolvedProject + truncated bool mu sync.Mutex hosts []string @@ -38,7 +39,7 @@ func newProjectsServer(t *testing.T, unresolved ...UnresolvedProject) *projectsS var body unresolvedProjectsRequest require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) ps.hosts = body.Hosts - _ = json.NewEncoder(w).Encode(unresolvedProjectsResponse{Projects: ps.unresolved}) + _ = json.NewEncoder(w).Encode(unresolvedProjectsResponse{Projects: ps.unresolved, Truncated: ps.truncated}) case "/api/v1/cc/projects/repositories": var body projectRepositoriesRequest require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) @@ -84,6 +85,18 @@ func TestMigrateProjectRepositories(t *testing.T) { require.Len(t, ps.moved, 1) assert.Equal(t, result.Linked, ps.moved[0]) assert.Equal(t, 3, result.Sessions) + assert.False(t, result.Truncated) + + ps.truncated = true + result, err = MigrateProjectRepositories(context.Background(), endpoint, []string{"mbp"}, repos, true) + require.NoError(t, err) + assert.True(t, result.Truncated, "a list the server cut short is reported") +} + +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) { @@ -109,6 +122,8 @@ func TestProjectMigrationHosts(t *testing.T) { 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) { From f116c7687147f24276cbf41c6703bdd268a9b57d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:10:55 +0000 Subject: [PATCH 03/11] fix(daemon): finish the project migration only when every folder was checked Second review round: - The migration pages through the server's listing by its last project, since folders it can't move stay listed; a run covers 50 pages. - A folder git couldn't answer for (timeout, git missing) counts as unchecked, not "no repository", and keeps the migration from writing its done marker; so does a machine without a host name of its own. - Lookups that timed out are remembered for 30 s, so a hung mount doesn't cost every OTLP export the whole budget. - A repository the agent named on the resource keeps the folder's off metrics too, and git isn't asked then. - `shelltime cc projects` is skipped in AI cloud only mode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- CLAUDE.md | 4 +- commands/aicode_projects.go | 8 ++- commands/aicode_projects_test.go | 12 ++++ daemon/aicode_otel_processor.go | 16 +++-- daemon/aicode_otel_repository_test.go | 7 +++ daemon/project_migration.go | 22 +++++-- daemon/project_migration_test.go | 28 +++++++++ model/api_project_repositories.go | 23 +++++-- model/git_repository.go | 56 +++++++++++------ model/git_repository_test.go | 27 +++++--- model/project_migration.go | 88 +++++++++++++++++---------- model/project_migration_test.go | 69 ++++++++++++++++++--- 12 files changed, 277 insertions(+), 83 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 04bb403..04db2e5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,8 +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. It caches definitive answers, negative ones too (10 min in the daemon), never a timeout or git failing to start. `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 records whose resource has a `pwd` and that don't name one (Claude Code's own value wins), 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) -- **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`; a 404 from an older server, a failure or a list the server marked `truncated` 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` 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) +- **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. 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 records whose resource has a `pwd` and that don't name one, 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) +- **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/commands/aicode_projects.go b/commands/aicode_projects.go index cd89eeb..cbea365 100644 --- a/commands/aicode_projects.go +++ b/commands/aicode_projects.go @@ -46,6 +46,9 @@ func commandAICodeProjects(c *cli.Context) error { if cfg.Token == "" { return errors.New("no ShellTime token configured, run `shelltime init` first") } + if skippedInAICloudOnly(cfg, "Projects not grouped") { + return nil + } endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint} hosts := model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) dryRun := c.Bool("dry-run") @@ -79,8 +82,11 @@ func commandAICodeProjects(c *cli.Context) error { 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("The server listed only part of this machine's folder projects; run it again to check the rest.") + color.Yellow.Println("This machine has more folder projects than one run goes through; run it again to check the rest.") } switch { case dryRun: diff --git a/commands/aicode_projects_test.go b/commands/aicode_projects_test.go index ed0ad04..16de1ec 100644 --- a/commands/aicode_projects_test.go +++ b/commands/aicode_projects_test.go @@ -55,6 +55,18 @@ func TestAICodeProjectsMovesClones(t *testing.T) { 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") diff --git a/daemon/aicode_otel_processor.go b/daemon/aicode_otel_processor.go index 09e1704..fca666c 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -78,17 +78,22 @@ func NewAICodeOtelProcessor(config model.ShellTimeConfig) *AICodeOtelProcessor { const repositoryCacheTTL = 10 * time.Minute // resolveRepository returns the canonical URL of the repository the resource's working -// directory belongs to, or "". +// 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 "" + } return p.repos.Resolve(ctx, res.attrs.Pwd).URL } -// fillRepository adds the resource's repository to a record that doesn't name one yet. It is -// seeded before the record's own attributes, so a vcs.repository.url.full that Claude Code -// sent on the record still wins. +// 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 @@ -96,6 +101,9 @@ func fillRepository(attrs map[string]any, res *otelResource) map[string]any { 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) } diff --git a/daemon/aicode_otel_repository_test.go b/daemon/aicode_otel_repository_test.go index abed260..8c6dd07 100644 --- a/daemon/aicode_otel_repository_test.go +++ b/daemon/aicode_otel_repository_test.go @@ -60,9 +60,16 @@ func TestRepositoryFromWorkingDirectory(t *testing.T) { 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) { diff --git a/daemon/project_migration.go b/daemon/project_migration.go index 55de2ee..5be3596 100644 --- a/daemon/project_migration.go +++ b/daemon/project_migration.go @@ -20,13 +20,18 @@ const projectMigrationDelay = 2 * time.Minute // 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, or a -// list the server cut short leaves none, so the next start tries again. `shelltime cc projects` -// runs it by hand. +// 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"` @@ -48,7 +53,13 @@ func runProjectMigrationOnce(ctx context.Context, cfg model.ShellTimeConfig, del } endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint} - hosts := model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) + 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 @@ -60,7 +71,7 @@ func runProjectMigrationOnce(ctx context.Context, cfg model.ShellTimeConfig, del return } - if !result.Truncated { + if result.Complete() { marker, _ := json.Marshal(projectMigrationMarker{ MigratedAt: time.Now().UTC(), Checked: result.Checked, @@ -81,5 +92,6 @@ func runProjectMigrationOnce(ctx context.Context, cfg model.ShellTimeConfig, del 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 index 884a5d3..568948c 100644 --- a/daemon/project_migration_test.go +++ b/daemon/project_migration_test.go @@ -15,7 +15,16 @@ import ( "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 @@ -49,7 +58,24 @@ func TestRunProjectMigrationOnce(t *testing.T) { 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}) })) @@ -61,6 +87,7 @@ func TestRunProjectMigrationOnceRetriesATruncatedList(t *testing.T) { } 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{}}) })) @@ -76,6 +103,7 @@ func TestRunProjectMigrationOnceSurvivesAnUnwritableMarker(t *testing.T) { } func TestRunProjectMigrationOnceRetriesLater(t *testing.T) { + withMigrationHosts(t, "mbp") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) })) diff --git a/model/api_project_repositories.go b/model/api_project_repositories.go index e7130bb..9068631 100644 --- a/model/api_project_repositories.go +++ b/model/api_project_repositories.go @@ -30,11 +30,18 @@ type ProjectRepository struct { 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 the server matched more folders than it listed. + // Truncated is true when more folders follow this page. Truncated bool `json:"truncated"` } @@ -46,20 +53,24 @@ type projectRepositoriesResponse struct { Updated int `json:"updated"` } -// FetchUnresolvedProjects lists the folder projects of the given hosts, the names this machine -// has reported its sessions under. truncated is true when the server matched more than it -// listed. -func FetchUnresolvedProjects(ctx context.Context, endpoint Endpoint, hosts []string) (projects []UnresolvedProject, truncated bool, err error) { +// 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: &unresolvedProjectsRequest{Hosts: hosts}, + Payload: req, Response: &resp, Timeout: 30 * time.Second, }) diff --git a/model/git_repository.go b/model/git_repository.go index 1ea067c..209dcc4 100644 --- a/model/git_repository.go +++ b/model/git_repository.go @@ -88,7 +88,11 @@ type GitRepository struct { 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 + 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 gitRepositoryMaxEntries = 512 ) @@ -101,9 +105,10 @@ 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 definitive answers for a while, negative ones included: the daemon asks for the same -// few directories on every OTEL export and statusline render. Concurrent lookups of one -// directory share one run of git. +// 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 // git runs git with args in dir; tests replace it. @@ -116,13 +121,15 @@ type GitRepositoryResolver struct { } type gitRepositoryEntry struct { - repo GitRepository - expires time.Time + repo GitRepository + definitive bool + expires time.Time } type gitRepositoryCall struct { - done chan struct{} - repo GitRepository + done chan struct{} + repo GitRepository + definitive bool } // NewGitRepositoryResolver returns a resolver that keeps answers for ttl (0 keeps nothing). @@ -168,27 +175,34 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) { // 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{} + return GitRepository{}, true } dir = filepath.Clean(dir) if dir == string(filepath.Separator) { - return GitRepository{} + return GitRepository{}, true } r.mu.Lock() if e, ok := r.cache[dir]; ok && r.now().Before(e.expires) { r.mu.Unlock() - return e.repo + return e.repo, e.definitive } if call, ok := r.inflight[dir]; ok { r.mu.Unlock() select { case <-call.done: - return call.repo + return call.repo, call.definitive case <-ctx.Done(): - return GitRepository{} + return GitRepository{}, false } } call := &gitRepositoryCall{done: make(chan struct{})} @@ -202,9 +216,9 @@ func (r *GitRepositoryResolver) Resolve(ctx context.Context, dir string) GitRepo cancel() r.mu.Lock() - call.repo = repo + call.repo, call.definitive = repo, definitive delete(r.inflight, dir) - if definitive && r.ttl > 0 { + if ttl := r.entryTTL(definitive); ttl > 0 { now := r.now() if len(r.cache) >= gitRepositoryMaxEntries { for k, e := range r.cache { @@ -216,11 +230,19 @@ func (r *GitRepositoryResolver) Resolve(ctx context.Context, dir string) GitRepo clear(r.cache) } } - r.cache[dir] = gitRepositoryEntry{repo: repo, expires: now.Add(r.ttl)} + r.cache[dir] = gitRepositoryEntry{repo: repo, definitive: definitive, expires: now.Add(ttl)} } r.mu.Unlock() close(call.done) - return repo + return repo, definitive +} + +// 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 diff --git a/model/git_repository_test.go b/model/git_repository_test.go index c9222cf..a8d3cc6 100644 --- a/model/git_repository_test.go +++ b/model/git_repository_test.go @@ -129,13 +129,15 @@ func TestGitRepositoryResolverCachesNegativeAnswers(t *testing.T) { assert.Equal(t, 1, git.calls) } -// A timeout, or git failing to start, says nothing about the directory: the next lookup asks -// again instead of serving a cached "no repository" for the whole TTL. +// 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 - r := NewGitRepositoryResolver(time.Minute) + 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 { @@ -144,12 +146,23 @@ func TestGitRepositoryResolverDoesNotCacheTransientFailures(t *testing.T) { return (&fakeGit{root: dir, remotes: "origin", url: "https://github.com/acme/web"}).run(ctx, d, args...) } - assert.Equal(t, GitRepository{}, r.Resolve(context.Background(), dir)) + repo, definitive := r.Lookup(context.Background(), dir) + assert.Equal(t, GitRepository{}, repo) + assert.False(t, definitive, "unknown, not no repository") failing = false - assert.Equal(t, "https://github.com/acme/web", r.Resolve(context.Background(), dir).URL) - assert.Equal(t, 4, calls, "the failed lookup was not cached") + _, 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, "the answer was") + assert.Equal(t, 4, calls, "a definitive answer is kept for the TTL") } // Concurrent lookups of one directory share one run of git. diff --git a/model/project_migration.go b/model/project_migration.go index 07af211..5144b8b 100644 --- a/model/project_migration.go +++ b/model/project_migration.go @@ -60,6 +60,10 @@ func ProjectMigrationHosts(settingsMachineName string) []string { return hosts } +// projectMigrationMaxPages bounds one migration run: 50 pages of the server's listing (2000 +// folders each). +const projectMigrationMaxPages = 50 + // ProjectMigrationResult is what a project migration found and did. type ProjectMigrationResult struct { // Checked counts the folder projects the server listed for this machine. @@ -73,53 +77,75 @@ type ProjectMigrationResult struct { Missing int // NotRepositories counts folders outside a git work tree, or in one without a remote. NotRepositories int - // Truncated is true when the server matched more folders than it listed; a later run sees - // the rest, once the folders this one moved are gone from the list. + // 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, 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. +// 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 } - projects, truncated, err := FetchUnresolvedProjects(ctx, endpoint, hosts) - if err != nil { - return result, err - } - result.Checked = len(projects) - result.Truncated = truncated - for _, p := range projects { - if err := ctx.Err(); err != nil { + var after *UnresolvedProject + for page := 0; page < projectMigrationMaxPages; page++ { + projects, truncated, err := FetchUnresolvedProjects(ctx, endpoint, hosts, after) + if err != nil { return result, err } - if info, err := os.Stat(p.Pwd); err != nil || !info.IsDir() { - result.Missing++ - continue + result.Checked += len(projects) + result.Truncated = truncated + + var linked []ProjectRepository + for _, p := range projects { + if err := ctx.Err(); err != nil { + return result, err + } + if info, err := os.Stat(p.Pwd); err != nil || !info.IsDir() { + 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}) + } } - repo := repos.Resolve(ctx, p.Pwd) - if repo.URL == "" { - result.NotRepositories++ - continue + 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 + } } - result.Linked = append(result.Linked, ProjectRepository{Host: p.Host, Pwd: p.Pwd, Repository: repo.URL}) - } - if dryRun { - return result, nil - } - for start := 0; start < len(result.Linked); start += ProjectRepositoriesMaxProjects { - end := min(start+ProjectRepositoriesMaxProjects, len(result.Linked)) - updated, err := SendProjectRepositories(ctx, endpoint, result.Linked[start:end]) - if err != nil { - return result, err + if !truncated || len(projects) == 0 { + break } - result.Sessions += updated + after = &projects[len(projects)-1] } return result, nil } diff --git a/model/project_migration_test.go b/model/project_migration_test.go index 0f5804a..39e1570 100644 --- a/model/project_migration_test.go +++ b/model/project_migration_test.go @@ -3,6 +3,7 @@ package model import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "os" @@ -20,11 +21,13 @@ import ( type projectsServer struct { server *httptest.Server unresolved []UnresolvedProject - truncated bool + // pageSize pages the listing like the server, by the last project sent; 0 sends it whole. + pageSize int - mu sync.Mutex - hosts []string - moved [][]ProjectRepository + mu sync.Mutex + hosts []string + afters []*unresolvedProjectCursor + moved [][]ProjectRepository } func newProjectsServer(t *testing.T, unresolved ...UnresolvedProject) *projectsServer { @@ -39,7 +42,20 @@ func newProjectsServer(t *testing.T, unresolved ...UnresolvedProject) *projectsS var body unresolvedProjectsRequest require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) ps.hosts = body.Hosts - _ = json.NewEncoder(w).Encode(unresolvedProjectsResponse{Projects: ps.unresolved, Truncated: ps.truncated}) + 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)) @@ -65,7 +81,7 @@ func TestMigrateProjectRepositories(t *testing.T) { repos := NewGitRepositoryResolver(time.Minute) repos.git = func(_ context.Context, dir string, args ...string) (string, error) { if dir != clone { - return "", os.ErrNotExist + 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...) } @@ -85,12 +101,42 @@ func TestMigrateProjectRepositories(t *testing.T) { require.Len(t, ps.moved, 1) assert.Equal(t, result.Linked, ps.moved[0]) assert.Equal(t, 3, result.Sessions) - assert.False(t, result.Truncated) + assert.True(t, result.Complete()) +} - ps.truncated = true - result, err = MigrateProjectRepositories(context.Background(), endpoint, []string{"mbp"}, repos, true) +// 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.True(t, result.Truncated, "a list the server cut short is reported") + 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) } func TestMigrateProjectRepositoriesWithoutHosts(t *testing.T) { @@ -115,6 +161,9 @@ func TestMigrateProjectRepositoriesReportsServerErrors(t *testing.T) { 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]) From e29ee39ee5523935d4487d0ebaf32171cca380e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:23:55 +0000 Subject: [PATCH 04/11] fix(model): bound repository lookups and let users turn them off Fourth review round: - A lookup runs on its own goroutine and is given up on after its budget, since a stat or git blocked on a hung network mount ignores the context; the directory gets no second lookup until it returns, and waiters are always released. The migration's folder check is bounded the same way and counts a hung folder as unchecked. - git refusing an untrusted repository (safe.directory) or killed by a signal is no definitive answer, so the migration retries the folder. - A git binary not found when the daemon started is looked for again every 30 s instead of never. - aiCodeOtel.sendRepository: false stops every lookup, removes the repository Claude Code reports, and skips the migration. - The projects command test no longer depends on the host name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- CLAUDE.md | 2 +- README.md | 4 +- commands/aicode_backfill.go | 4 +- commands/aicode_projects.go | 11 ++- commands/aicode_projects_test.go | 5 ++ daemon/aicode_otel_processor.go | 16 +++- daemon/aicode_otel_repository_test.go | 31 +++++++ daemon/project_migration.go | 2 +- daemon/socket.go | 11 ++- model/git_repository.go | 124 ++++++++++++++++++++++---- model/git_repository_test.go | 67 ++++++++++++++ model/project_migration.go | 7 +- model/types.go | 11 +++ 13 files changed, 271 insertions(+), 24 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 04db2e5..7d5e831 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,7 +105,7 @@ 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. 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 records whose resource has a `pwd` and that don't name one, 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) +- **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`) and the directory gets no other until it returns. 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 records whose resource has a `pwd` and that don't name one, 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 521d116..2f71168 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,9 @@ Besides tokens and cost, both tools then send your prompts, tool details (shell 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 host names many machines share, like `localhost`, are skipped. +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 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. ## Codex Usage Tracking diff --git a/commands/aicode_backfill.go b/commands/aicode_backfill.go index 5ea44f9..1f93041 100644 --- a/commands/aicode_backfill.go +++ b/commands/aicode_backfill.go @@ -151,7 +151,9 @@ func runAICodeBackfill(c *cli.Context, src aiCodeBackfillSource) error { } // The server groups sessions into projects by git repository when it knows it. - model.AttachBackfillRepositories(ctx, plan.upload, model.NewGitRepositoryResolver(time.Hour)) + 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) diff --git a/commands/aicode_projects.go b/commands/aicode_projects.go index cbea365..eaec1a9 100644 --- a/commands/aicode_projects.go +++ b/commands/aicode_projects.go @@ -34,6 +34,11 @@ var AICodeProjectsCommand = &cli.Command{ 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() @@ -49,8 +54,12 @@ func commandAICodeProjects(c *cli.Context) error { 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 := model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName()) + hosts := aiCodeProjectsHosts() dryRun := c.Bool("dry-run") color.Yellow.Println("Looking for projects grouped by folder...") diff --git a/commands/aicode_projects_test.go b/commands/aicode_projects_test.go index 16de1ec..c83b140 100644 --- a/commands/aicode_projects_test.go +++ b/commands/aicode_projects_test.go @@ -37,6 +37,11 @@ func TestAICodeProjectsMovesClones(t *testing.T) { require.NoError(t, err, string(out)) } + // 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 }) + var moves int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { diff --git a/daemon/aicode_otel_processor.go b/daemon/aicode_otel_processor.go index fca666c..33512f1 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -43,6 +43,9 @@ type AICodeOtelProcessor struct { // 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 @@ -58,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, @@ -68,7 +75,8 @@ func NewAICodeOtelProcessor(config model.ShellTimeConfig) *AICodeOtelProcessor { hostname: hostname, debug: debug, cloudSessionID: model.CloudSessionIDFromEnv(os.Getenv), - repos: model.NewGitRepositoryResolver(repositoryCacheTTL), + repos: repos, + dropRepository: !config.SendsRepository(), maxRequestBytes: model.AICodeOtelMaxRequestBytes, } } @@ -719,6 +727,9 @@ func (p *AICodeOtelProcessor) parseMetric(m *metricsv1.Metric, res *otelResource for _, attr := range dp.GetAttributes() { applyMetricAttribute(&metric, attr, metricType) } + if p.dropRepository { + delete(metric.Attributes, model.AICodeRepositoryAttribute) + } metrics = append(metrics, metric) } @@ -816,6 +827,9 @@ func (p *AICodeOtelProcessor) parseLogRecord(lr *logsv1.LogRecord, res *otelReso 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 index 8c6dd07..b9f12d5 100644 --- a/daemon/aicode_otel_repository_test.go +++ b/daemon/aicode_otel_repository_test.go @@ -86,3 +86,34 @@ func TestRepositoryNeedsAWorkingDirectory(t *testing.T) { 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{})) +} diff --git a/daemon/project_migration.go b/daemon/project_migration.go index 5be3596..87947f9 100644 --- a/daemon/project_migration.go +++ b/daemon/project_migration.go @@ -40,7 +40,7 @@ type projectMigrationMarker struct { } func runProjectMigrationOnce(ctx context.Context, cfg model.ShellTimeConfig, delay time.Duration, markerPath string) { - if cfg.Token == "" { + if cfg.Token == "" || !cfg.SendsRepository() { return } if _, err := os.Stat(markerPath); err == nil { diff --git a/daemon/socket.go b/daemon/socket.go index 8215e49..a5d9c59 100644 --- a/daemon/socket.go +++ b/daemon/socket.go @@ -127,10 +127,19 @@ func NewSocketHandler(config *model.ShellTimeConfig, ch *GoChannel) *SocketHandl stopChan: make(chan struct{}), ccInfoTimer: NewCCInfoTimerService(config), aiCloudOnly: model.IsAICloudOnly(*config, os.Getenv), - repos: model.NewGitRepositoryResolver(repositoryCacheTTL), + 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) { diff --git a/model/git_repository.go b/model/git_repository.go index 209dcc4..d4cbc03 100644 --- a/model/git_repository.go +++ b/model/git_repository.go @@ -93,12 +93,16 @@ const ( // 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 or git failing to start, which say nothing about the -// directory and are not cached. +// 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() } @@ -111,6 +115,8 @@ func (e gitExitError) Unwrap() error { return e.err } // 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 @@ -118,6 +124,9 @@ type GitRepositoryResolver struct { 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 { @@ -136,26 +145,37 @@ type gitRepositoryCall struct { 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 ( - gitBinaryOnce sync.Once - gitBinary = "git" + gitBinaryMu sync.Mutex + gitBinary string + gitBinaryLookedAt time.Time ) -// gitExecutable finds git once, also where the daemon's limited PATH doesn't reach (Homebrew, -// /usr/local/bin), through the CommandService's fallback paths. +// 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 { - gitBinaryOnce.Do(func() { + 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 } @@ -166,12 +186,25 @@ func runGit(ctx context.Context, dir string, args ...string) (string, error) { cmd.Env = append(os.Environ(), "GIT_OPTIONAL_LOCKS=0", "GIT_TERMINAL_PROMPT=0") out, err := cmd.Output() var exitErr *exec.ExitError - if err != nil && errors.As(err, &exitErr) && ctx.Err() == nil { + 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 { @@ -196,6 +229,10 @@ func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepo 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 { @@ -209,13 +246,53 @@ func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepo r.inflight[dir] = call r.mu.Unlock() + var repo GitRepository + var definitive bool + // Every waiter is released however this ends. + defer func() { + r.finish(dir, call, repo, definitive) + close(call.done) + }() + // The lookup isn't tied to this caller's context, so a caller that gives up doesn't spoil - // the answer for the others waiting on it; the budget bounds it instead. - lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), gitRepositoryTimeout) - repo, definitive := r.lookup(lookupCtx, dir) - cancel() + // the answer for the others waiting on it; the budget bounds it instead. It runs on its own + // goroutine because the budget can't interrupt a stat or a git run blocked in the kernel. + type answer struct { + repo GitRepository + definitive bool + } + answers := make(chan answer, 1) + timeout := r.timeout + go func() { + lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout) + defer cancel() + a := answer{} + a.repo, a.definitive = r.lookup(lookupCtx, dir) + answers <- a + }() + timer := time.NewTimer(timeout + gitRepositoryGrace) + defer timer.Stop() + select { + case a := <-answers: + repo, definitive = a.repo, a.definitive + case <-timer.C: + r.mu.Lock() + r.stuck[dir] = struct{}{} + r.mu.Unlock() + go func() { + <-answers + r.mu.Lock() + delete(r.stuck, dir) + r.mu.Unlock() + }() + } + return repo, definitive +} +// 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) if ttl := r.entryTTL(definitive); ttl > 0 { @@ -232,9 +309,24 @@ func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepo } r.cache[dir] = gitRepositoryEntry{repo: repo, definitive: definitive, expires: now.Add(ttl)} } - r.mu.Unlock() - close(call.done) - return repo, definitive +} + +// statDir reports whether dir is a directory. ok is false when the stat didn't return within +// timeout: on a hung network mount it blocks in the kernel, where no context reaches it. +func statDir(dir string, timeout time.Duration) (isDir, ok bool) { + result := make(chan bool, 1) + go func() { + info, err := os.Stat(dir) + result <- err == nil && info.IsDir() + }() + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case isDir := <-result: + return isDir, true + case <-timer.C: + return false, false + } } // entryTTL is how long an answer is kept. diff --git a/model/git_repository_test.go b/model/git_repository_test.go index a8d3cc6..05e5295 100644 --- a/model/git_repository_test.go +++ b/model/git_repository_test.go @@ -6,7 +6,9 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "sync" + "sync/atomic" "testing" "time" @@ -221,6 +223,71 @@ func TestGitRepositoryResolverWaiterGivesUp(t *testing.T) { 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) +} + +// 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]bool{dir: true, file: false, filepath.Join(dir, "missing"): false} { + isDir, ok := statDir(path, time.Second) + assert.True(t, ok) + assert.Equal(t, want, isDir, path) + } +} + func TestGitRepositoryResolverSkipsWhatIsNotADirectory(t *testing.T) { git := &fakeGit{root: "/x", remotes: "origin", url: "https://github.com/a/b"} r := NewGitRepositoryResolver(time.Minute) diff --git a/model/project_migration.go b/model/project_migration.go index 5144b8b..abf4c71 100644 --- a/model/project_migration.go +++ b/model/project_migration.go @@ -115,7 +115,12 @@ func MigrateProjectRepositories(ctx context.Context, endpoint Endpoint, hosts [] if err := ctx.Err(); err != nil { return result, err } - if info, err := os.Stat(p.Pwd); err != nil || !info.IsDir() { + isDir, ok := statDir(p.Pwd, repos.timeout) + if !ok { + result.Unchecked++ + continue + } + if !isDir { result.Missing++ continue } 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 From 8e4e5d83c63609256f1358cf889614a8c06ea32c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:28:52 +0000 Subject: [PATCH 05/11] fix(daemon): drop the repository from spans when it isn't to be sent aiCodeOtel.sendRepository: false removed the repository from metrics and events but not from trace spans and their events, which now lose it too. The README says the daemon needs a restart for the switch, and every projects command test names the machine itself instead of relying on the host name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- README.md | 2 +- commands/aicode_projects_test.go | 10 +++++----- daemon/aicode_otel_processor.go | 12 ++++++++++++ daemon/aicode_otel_traces_test.go | 21 +++++++++++++++++++++ 4 files changed, 39 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 2f71168..20f7a82 100644 --- a/README.md +++ b/README.md @@ -207,7 +207,7 @@ ShellTime groups your coding agent sessions into projects by the git repository 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 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. +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 diff --git a/commands/aicode_projects_test.go b/commands/aicode_projects_test.go index c83b140..8f6afb7 100644 --- a/commands/aicode_projects_test.go +++ b/commands/aicode_projects_test.go @@ -23,6 +23,11 @@ func runProjects(t *testing.T, group string, token, endpoint string, args ...str 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...)) } @@ -37,11 +42,6 @@ func TestAICodeProjectsMovesClones(t *testing.T) { require.NoError(t, err, string(out)) } - // 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 }) - var moves int server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { diff --git a/daemon/aicode_otel_processor.go b/daemon/aicode_otel_processor.go index 33512f1..2448a55 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -332,6 +332,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) } } @@ -429,6 +432,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) { 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) +} From e5828fd592d38eb03bfc08766925a196daf3c2d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:38:52 +0000 Subject: [PATCH 06/11] fix(model): escape repository names and read git's messages in English Fifth review round: - Each path segment of a remote is decoded and escaped again, like the server, so "My%20Project" stays one name, "repo%23one" doesn't lose its tail to a fragment, and every spelling of a name gives one URL. - git runs with LC_ALL=C, since gitExitIsAnswer reads its messages; a translated safe.directory refusal no longer counts as "no repository". - A caller whose context ends stops waiting for a lookup, whose answer is kept for the next caller. - A migration run stops asking after three folders went unanswered, so a hung mount costs a few blocked threads, not one per folder. - The docs say spans get no repository from the folder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- CLAUDE.md | 2 +- model/git_repository.go | 55 +++++++++++++++++++++++---------- model/git_repository_test.go | 35 +++++++++++++++++++++ model/project_migration.go | 13 ++++++++ model/project_migration_test.go | 25 +++++++++++++++ 5 files changed, 113 insertions(+), 17 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7d5e831..418d87b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,7 +105,7 @@ 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`) and the directory gets no other until it returns. 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 records whose resource has a `pwd` and that don't name one, 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 +- **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 went unanswered. 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/model/git_repository.go b/model/git_repository.go index d4cbc03..aba8807 100644 --- a/model/git_repository.go +++ b/model/git_repository.go @@ -54,6 +54,9 @@ func CanonicalRepositoryURL(remote string) (string, bool) { host = host[at+1:] } path = remote[colon+1:] + if unescaped, err := url.PathUnescape(path); err == nil { + path = unescaped + } } host = strings.ToLower(strings.TrimSuffix(host, ".")) @@ -73,6 +76,12 @@ func CanonicalRepositoryURL(remote string) (string, bool) { 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 } @@ -135,6 +144,11 @@ type gitRepositoryEntry struct { expires time.Time } +type gitRepositoryAnswer struct { + repo GitRepository + definitive bool +} + type gitRepositoryCall struct { done chan struct{} repo GitRepository @@ -183,7 +197,8 @@ func gitExecutable() string { // 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...)...) - cmd.Env = append(os.Environ(), "GIT_OPTIONAL_LOCKS=0", "GIT_TERMINAL_PROMPT=0") + // 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) { @@ -257,16 +272,12 @@ func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepo // The lookup isn't tied to this caller's context, so a caller that gives up doesn't spoil // the answer for the others waiting on it; the budget bounds it instead. It runs on its own // goroutine because the budget can't interrupt a stat or a git run blocked in the kernel. - type answer struct { - repo GitRepository - definitive bool - } - answers := make(chan answer, 1) + answers := make(chan gitRepositoryAnswer, 1) timeout := r.timeout go func() { lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeout) defer cancel() - a := answer{} + a := gitRepositoryAnswer{} a.repo, a.definitive = r.lookup(lookupCtx, dir) answers <- a }() @@ -275,20 +286,32 @@ func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepo select { case a := <-answers: repo, definitive = a.repo, a.definitive + case <-ctx.Done(): + // This caller gave up (its exporter went away, the daemon is stopping). + r.abandon(dir, answers) case <-timer.C: - r.mu.Lock() - r.stuck[dir] = struct{}{} - r.mu.Unlock() - go func() { - <-answers - r.mu.Lock() - delete(r.stuck, dir) - r.mu.Unlock() - }() + r.abandon(dir, answers) } return repo, definitive } +// abandon stops waiting for a lookup that is still running: the directory gets no other lookup +// until this one returns, and its answer is kept then for whoever asks next. +func (r *GitRepositoryResolver) abandon(dir string, answers <-chan gitRepositoryAnswer) { + r.mu.Lock() + r.stuck[dir] = struct{}{} + r.mu.Unlock() + 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() diff --git a/model/git_repository_test.go b/model/git_repository_test.go index 05e5295..ea5c58d 100644 --- a/model/git_repository_test.go +++ b/model/git_repository_test.go @@ -45,6 +45,20 @@ func TestCanonicalRepositoryURL(t *testing.T) { } } +// 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{ "", @@ -259,6 +273,27 @@ func TestGitRepositoryResolverGivesUpOnAStuckLookup(t *testing.T) { 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) + + close(release) + assert.Eventually(t, func() bool { + repo, definitive := r.Lookup(context.Background(), dir) + return definitive && repo.URL == "https://github.com/acme/web" + }, 2*time.Second, 10*time.Millisecond) +} + // 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) { diff --git a/model/project_migration.go b/model/project_migration.go index abf4c71..00b0ddc 100644 --- a/model/project_migration.go +++ b/model/project_migration.go @@ -64,6 +64,12 @@ func ProjectMigrationHosts(settingsMachineName string) []string { // folders each). const projectMigrationMaxPages = 50 +// projectMigrationMaxUnanswered is how many folders may go unanswered (a stat or git that +// timed out, as on 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. +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. @@ -102,6 +108,7 @@ func MigrateProjectRepositories(ctx context.Context, endpoint Endpoint, hosts [] } var after *UnresolvedProject + unanswered := 0 for page := 0; page < projectMigrationMaxPages; page++ { projects, truncated, err := FetchUnresolvedProjects(ctx, endpoint, hosts, after) if err != nil { @@ -115,8 +122,13 @@ func MigrateProjectRepositories(ctx context.Context, endpoint Endpoint, hosts [] if err := ctx.Err(); err != nil { return result, err } + if unanswered >= projectMigrationMaxUnanswered { + result.Unchecked++ + continue + } isDir, ok := statDir(p.Pwd, repos.timeout) if !ok { + unanswered++ result.Unchecked++ continue } @@ -127,6 +139,7 @@ func MigrateProjectRepositories(ctx context.Context, endpoint Endpoint, hosts [] repo, definitive := repos.Lookup(ctx, p.Pwd) switch { case !definitive: + unanswered++ result.Unchecked++ case repo.URL == "": result.NotRepositories++ diff --git a/model/project_migration_test.go b/model/project_migration_test.go index 39e1570..9a3bd64 100644 --- a/model/project_migration_test.go +++ b/model/project_migration_test.go @@ -139,6 +139,31 @@ func TestMigrateProjectRepositoriesCountsUncheckedFolders(t *testing.T) { assert.Empty(t, ps.moved) } +// After a few folders go unanswered, a run stops asking about the rest. +func TestMigrateProjectRepositoriesStopsAskingWhenUnanswered(t *testing.T) { + var projects []UnresolvedProject + for range 6 { + projects = append(projects, UnresolvedProject{Host: "mbp", Pwd: t.TempDir()}) + } + ps := newProjectsServer(t, projects...) + var mu sync.Mutex + asked := map[string]bool{} + repos := NewGitRepositoryResolver(time.Minute) + repos.git = func(_ context.Context, dir string, _ ...string) (string, error) { + mu.Lock() + asked[dir] = true + mu.Unlock() + 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, 6, result.Unchecked) + assert.False(t, result.Complete()) + mu.Lock() + defer mu.Unlock() + assert.Len(t, asked, projectMigrationMaxUnanswered) +} + 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") From a58c002211855119c5eaf72eb05846dd85745cec Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:43:58 +0000 Subject: [PATCH 07/11] fix(model): stop a migration run only for hung stats The run stopped asking after three folders went unanswered, which also counted folders git refuses (safe.directory), so three such folders kept every later folder unchecked on every run. Only stats that time out count now. A folder that can't be stat'ed for another reason than not existing counts as unchecked, not missing; an abandoned lookup's answer is no longer overwritten by "unknown"; and `cc projects` names a generic host name before it starts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- CLAUDE.md | 2 +- README.md | 2 +- commands/aicode_projects.go | 6 ++--- model/git_repository.go | 39 ++++++++++++++++++++++++++------- model/git_repository_test.go | 6 ++--- model/project_migration.go | 19 ++++++++-------- model/project_migration_test.go | 27 +++++++++++++++++------ 7 files changed, 68 insertions(+), 33 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 418d87b..d0d837b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,7 +105,7 @@ 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 went unanswered. 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 +- **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 20f7a82..a398a40 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ Besides tokens and cost, both tools then send your prompts, tool details (shell 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 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. +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. diff --git a/commands/aicode_projects.go b/commands/aicode_projects.go index eaec1a9..9088ff7 100644 --- a/commands/aicode_projects.go +++ b/commands/aicode_projects.go @@ -60,6 +60,9 @@ func commandAICodeProjects(c *cli.Context) error { } 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...") @@ -73,9 +76,6 @@ func commandAICodeProjects(c *cli.Context) error { return fmt.Errorf("project migration failed: %w", err) } - 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") - } if result.Checked == 0 { color.Green.Println("Every project of this machine is already grouped by repository.") return nil diff --git a/model/git_repository.go b/model/git_repository.go index aba8807..c344dac 100644 --- a/model/git_repository.go +++ b/model/git_repository.go @@ -3,6 +3,7 @@ package model import ( "context" "errors" + "io/fs" "net/url" "os" "os/exec" @@ -318,6 +319,11 @@ func (r *GitRepositoryResolver) finish(dir string, call *gitRepositoryCall, repo 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 { @@ -334,21 +340,38 @@ func (r *GitRepositoryResolver) finish(dir string, call *gitRepositoryCall, repo } } -// statDir reports whether dir is a directory. ok is false when the stat didn't return within -// timeout: on a hung network mount it blocks in the kernel, where no context reaches it. -func statDir(dir string, timeout time.Duration) (isDir, ok bool) { - result := make(chan bool, 1) +// 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) - result <- err == nil && info.IsDir() + 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 isDir := <-result: - return isDir, true + case state := <-result: + return state case <-timer.C: - return false, false + return dirTimedOut } } diff --git a/model/git_repository_test.go b/model/git_repository_test.go index ea5c58d..356de60 100644 --- a/model/git_repository_test.go +++ b/model/git_repository_test.go @@ -316,10 +316,8 @@ 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]bool{dir: true, file: false, filepath.Join(dir, "missing"): false} { - isDir, ok := statDir(path, time.Second) - assert.True(t, ok) - assert.Equal(t, want, isDir, path) + 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) } } diff --git a/model/project_migration.go b/model/project_migration.go index 00b0ddc..719f8f8 100644 --- a/model/project_migration.go +++ b/model/project_migration.go @@ -64,10 +64,10 @@ func ProjectMigrationHosts(settingsMachineName string) []string { // folders each). const projectMigrationMaxPages = 50 -// projectMigrationMaxUnanswered is how many folders may go unanswered (a stat or git that -// timed out, as on 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. +// 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. @@ -126,20 +126,21 @@ func MigrateProjectRepositories(ctx context.Context, endpoint Endpoint, hosts [] result.Unchecked++ continue } - isDir, ok := statDir(p.Pwd, repos.timeout) - if !ok { + switch statDir(p.Pwd, repos.timeout) { + case dirTimedOut: unanswered++ result.Unchecked++ continue - } - if !isDir { + case dirUnknown: + result.Unchecked++ + continue + case dirMissing: result.Missing++ continue } repo, definitive := repos.Lookup(ctx, p.Pwd) switch { case !definitive: - unanswered++ result.Unchecked++ case repo.URL == "": result.NotRepositories++ diff --git a/model/project_migration_test.go b/model/project_migration_test.go index 9a3bd64..2732afa 100644 --- a/model/project_migration_test.go +++ b/model/project_migration_test.go @@ -139,29 +139,42 @@ func TestMigrateProjectRepositoriesCountsUncheckedFolders(t *testing.T) { assert.Empty(t, ps.moved) } -// After a few folders go unanswered, a run stops asking about the rest. +// 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(time.Minute) + repos := NewGitRepositoryResolver(0) repos.git = func(_ context.Context, dir string, _ ...string) (string, error) { mu.Lock() asked[dir] = true mu.Unlock() - return "", context.DeadlineExceeded + return "", context.DeadlineExceeded // or a safe.directory refusal: no answer } - result, err := MigrateProjectRepositories(context.Background(), Endpoint{Token: "tok", APIEndpoint: ps.server.URL}, []string{"mbp"}, repos, false) + 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()) - mu.Lock() - defer mu.Unlock() - assert.Len(t, asked, projectMigrationMaxUnanswered) + assert.Equal(t, projectMigrationMaxUnanswered, stats, "after a few hung stats the rest aren't asked about") } func TestMigrateProjectRepositoriesWithoutHosts(t *testing.T) { From c08b32a09721735bd019ca856987bd39c9b7bd3d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:46:50 +0000 Subject: [PATCH 08/11] fix(model): merge a local aiCodeOtel block field by field config.local.yaml replaced the whole aiCodeOtel block, so a local file that only set debug or the port turned the collector's base settings back to their defaults, sendRepository: false included, and the daemon started sending repository names again. The block now merges field by field, like codeTracking. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- model/config.go | 20 +++++++++++++++++++- model/config_test.go | 21 +++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) 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()) +} From 118fc32fe80926ef0c3c213f5bbf93ef0cfa42d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:49:55 +0000 Subject: [PATCH 09/11] fix(daemon): don't give a record in another folder the resource's repository A record that names a working directory of its own other than its resource's got the repository of the resource's folder, which may be another clone. The daemon now takes that repository back, as the server does for the statusline's directory; a repository the record names itself stays. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- daemon/aicode_otel_processor.go | 18 ++++++++++++++++++ daemon/aicode_otel_repository_test.go | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/daemon/aicode_otel_processor.go b/daemon/aicode_otel_processor.go index 2448a55..d3f55d2 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -115,6 +115,18 @@ func fillRepository(attrs map[string]any, res *otelResource) map[string]any { return setAttribute(attrs, model.AICodeRepositoryAttribute, res.repository) } +// unfillRepository takes back the repository fillRepository added when the record named a +// working directory of its own: the repository is the resource's folder's, not necessarily that +// one's. A repository the record itself named stays. +func unfillRepository(attrs map[string]any, res *otelResource, filled bool, pwd string) { + if !filled || pwd == "" || pwd == res.attrs.Pwd { + return + } + if attrs[model.AICodeRepositoryAttribute] == res.repository { + delete(attrs, model.AICodeRepositoryAttribute) + } +} + // 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. @@ -734,11 +746,14 @@ 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, metric.Pwd) if p.dropRepository { delete(metric.Attributes, model.AICodeRepositoryAttribute) } @@ -828,13 +843,16 @@ 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, event.Pwd) if event.SessionID == "" && event.ConversationID != "" { event.SessionID = event.ConversationID diff --git a/daemon/aicode_otel_repository_test.go b/daemon/aicode_otel_repository_test.go index b9f12d5..edec2a4 100644 --- a/daemon/aicode_otel_repository_test.go +++ b/daemon/aicode_otel_repository_test.go @@ -117,3 +117,26 @@ func TestRepositoryNotSentWhenTurnedOff(t *testing.T) { 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("/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") +} From 6a3c55f5f5f133d0c31a3ad122c71dcf3b36075b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:53:28 +0000 Subject: [PATCH 10/11] fix(daemon): keep the repository for records in a subfolder of the clone The previous change took the resource folder's repository back from any record naming another working directory, a subfolder of the same work tree too, which split the project. Records whose directory is inside the resource's work tree keep it now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- daemon/aicode_otel_processor.go | 22 ++++++++++++++++++---- daemon/aicode_otel_repository_test.go | 6 ++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/daemon/aicode_otel_processor.go b/daemon/aicode_otel_processor.go index d3f55d2..2802bdc 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -94,7 +94,18 @@ func (p *AICodeOtelProcessor) resolveRepository(ctx context.Context, res *otelRe if _, ok := res.attrs.Attributes[model.AICodeRepositoryAttribute]; ok { return "" } - return p.repos.Resolve(ctx, res.attrs.Pwd).URL + 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 @@ -116,10 +127,11 @@ func fillRepository(attrs map[string]any, res *otelResource) map[string]any { } // unfillRepository takes back the repository fillRepository added when the record named a -// working directory of its own: the repository is the resource's folder's, not necessarily that -// one's. A repository the record itself named stays. +// 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 { + if !filled || pwd == "" || pwd == res.attrs.Pwd || insideDir(pwd, res.repositoryRoot) { return } if attrs[model.AICodeRepositoryAttribute] == res.repository { @@ -178,6 +190,8 @@ type otelResource struct { // 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 diff --git a/daemon/aicode_otel_repository_test.go b/daemon/aicode_otel_repository_test.go index edec2a4..addc3af 100644 --- a/daemon/aicode_otel_repository_test.go +++ b/daemon/aicode_otel_repository_test.go @@ -3,6 +3,7 @@ package daemon import ( "context" "os/exec" + "path/filepath" "testing" "github.com/malamtime/cli/model" @@ -136,6 +137,11 @@ func TestRepositoryNotFilledForAnotherWorkingDirectory(t *testing.T) { 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/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") From 9c8e29e39841acdc6d62cdca9f825544d10287e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:55:06 +0000 Subject: [PATCH 11/11] fix(model): let a lookup outlive the caller that started it A caller whose context ended abandoned the lookup it had started, and every caller sharing it got "unknown" although git answered moments later. The lookup now runs on its own and publishes its answer to everyone waiting; only the budget turns it into "unknown". A record that names the same repository as its resource's folder keeps it even from another folder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRd5iov8tzMQ1SaQ2Fk --- daemon/aicode_otel_processor.go | 16 +++++++--- daemon/aicode_otel_repository_test.go | 4 +++ model/git_repository.go | 45 ++++++++++++++------------- model/git_repository_test.go | 12 ++++--- 4 files changed, 48 insertions(+), 29 deletions(-) diff --git a/daemon/aicode_otel_processor.go b/daemon/aicode_otel_processor.go index 2802bdc..3bc94d4 100644 --- a/daemon/aicode_otel_processor.go +++ b/daemon/aicode_otel_processor.go @@ -134,9 +134,17 @@ func unfillRepository(attrs map[string]any, res *otelResource, filled bool, pwd if !filled || pwd == "" || pwd == res.attrs.Pwd || insideDir(pwd, res.repositoryRoot) { return } - if attrs[model.AICodeRepositoryAttribute] == res.repository { - delete(attrs, model.AICodeRepositoryAttribute) + 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 @@ -767,7 +775,7 @@ func (p *AICodeOtelProcessor) parseMetric(m *metricsv1.Metric, res *otelResource for _, attr := range dp.GetAttributes() { applyMetricAttribute(&metric, attr, metricType) } - unfillRepository(metric.Attributes, res, has && !had, metric.Pwd) + unfillRepository(metric.Attributes, res, has && !had && !namesRepository(dp.GetAttributes()), metric.Pwd) if p.dropRepository { delete(metric.Attributes, model.AICodeRepositoryAttribute) } @@ -866,7 +874,7 @@ func (p *AICodeOtelProcessor) parseLogRecord(lr *logsv1.LogRecord, res *otelReso applyEventAttribute(event, &fallbacks, attr.GetKey(), attr.GetValue()) } fallbacks.apply(event, res.attrs) - unfillRepository(event.Attributes, res, has && !had, event.Pwd) + unfillRepository(event.Attributes, res, has && !had && !namesRepository(lr.GetAttributes()), event.Pwd) if event.SessionID == "" && event.ConversationID != "" { event.SessionID = event.ConversationID diff --git a/daemon/aicode_otel_repository_test.go b/daemon/aicode_otel_repository_test.go index addc3af..793639b 100644 --- a/daemon/aicode_otel_repository_test.go +++ b/daemon/aicode_otel_repository_test.go @@ -142,6 +142,10 @@ func TestRepositoryNotFilledForAnotherWorkingDirectory(t *testing.T) { 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/model/git_repository.go b/model/git_repository.go index c344dac..fefcaa5 100644 --- a/model/git_repository.go +++ b/model/git_repository.go @@ -262,21 +262,27 @@ func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepo r.inflight[dir] = call r.mu.Unlock() - var repo GitRepository - var definitive bool - // Every waiter is released however this ends. - defer func() { - r.finish(dir, call, repo, definitive) - close(call.done) - }() + // 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 + } +} - // The lookup isn't tied to this caller's context, so a caller that gives up doesn't spoil - // the answer for the others waiting on it; the budget bounds it instead. It runs on its own - // goroutine because the budget can't interrupt a stat or a git run blocked in the kernel. +// 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(context.WithoutCancel(ctx), timeout) + lookupCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() a := gitRepositoryAnswer{} a.repo, a.definitive = r.lookup(lookupCtx, dir) @@ -286,22 +292,19 @@ func (r *GitRepositoryResolver) Lookup(ctx context.Context, dir string) (GitRepo defer timer.Stop() select { case a := <-answers: - repo, definitive = a.repo, a.definitive - case <-ctx.Done(): - // This caller gave up (its exporter went away, the daemon is stopping). - r.abandon(dir, 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) } - return repo, definitive } -// abandon stops waiting for a lookup that is still running: the directory gets no other lookup -// until this one returns, and its answer is kept then for whoever asks next. +// 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) { - r.mu.Lock() - r.stuck[dir] = struct{}{} - r.mu.Unlock() go func() { a := <-answers r.mu.Lock() diff --git a/model/git_repository_test.go b/model/git_repository_test.go index 356de60..f01d0af 100644 --- a/model/git_repository_test.go +++ b/model/git_repository_test.go @@ -287,11 +287,15 @@ func TestGitRepositoryResolverCallerGivesUp(t *testing.T) { _, 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.Eventually(t, func() bool { - repo, definitive := r.Lookup(context.Background(), dir) - return definitive && repo.URL == "https://github.com/acme/web" - }, 2*time.Second, 10*time.Millisecond) + 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