Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ Optional daemon services (feature-gated via config):
- **CodexUsageSyncService**: Syncs Codex usage to `/api/v1/codex-usage` every 10 min, only while a `codex`/`chatgpt` process is running (both intervals share the `usageSyncInterval` const in `daemon/usage_sync.go`)
- **SyncCircuitBreakerService**: Retry failed syncs with file-based persistence (`~/.shelltime/sync-pending.jsonl`, one sync message per line, of any length) and hourly recovery timer. `SaveForRetry` and the timer's read-republish-rewrite share a lock, and the rewrite keeps lines saved while it was republishing
- **AICodeOtelServer**: gRPC OTEL collector for AI coding CLI metrics, logs and traces (Claude Code, Codex). Spans (`claude_code.interaction`, `llm_request`, `tool`, ...) go to the same `/api/v1/cc/otel` endpoint in `spans`; a span without `session.id` takes it from another span of its trace in the same export. `shelltime cc install` turns traces on (`CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`, `OTEL_TRACES_EXPORTER=otlp`). In a Claude Code cloud session (`CLAUDE_CODE_REMOTE=true`, where the SessionStart hook starts the daemon) it adds the VM's `CLAUDE_CODE_REMOTE_SESSION_ID` as the `ccr.session.id` attribute to Claude Code records that lack it; the server marks those sessions as cloud sessions. `daemon/main_test.go` clears both variables so tests behave the same inside a cloud session
- **Git repositories** (`model/git_repository.go`): the server groups coding agent sessions into projects by git repository, not folder, so a renamed or moved clone, a worktree or a subfolder stays one project. `GitRepositoryResolver` asks the git CLI (found through `CommandService`, so the daemon's limited PATH reaches Homebrew) for a directory's top level and its `origin` remote (else `upstream`, else the first by name; `remote get-url`, so `insteadOf` applies) without optional locks, within one 2 s budget per lookup, since the daemon resolves on the OTLP export path. Concurrent lookups of one directory share one run, which goes on its own goroutine: a stat or git blocked in the kernel (a hung network mount) ignores the context, so the lookup is given up on after the budget (plus `gitRepositoryGrace`), or when its caller's context ends, and the directory gets no other until it returns (its answer is kept then). git runs with `LC_ALL=C`, since its messages are read; a remote's path segments are decoded and escaped again (`url.PathEscape`), like the server's. A migration run stops asking after `projectMigrationMaxUnanswered` folders' stats timed out (a hung mount; git refusing a folder doesn't count), and a folder that doesn't exist counts as missing, one it can't stat otherwise as unchecked. git refusing a repository it doesn't trust (`safe.directory`) or killed by a signal is no answer about the directory; a git binary not found is looked for again every 30 s. It keeps definitive answers, negative ones too (10 min in the daemon), and a timeout or git failing to start for 30 s only, reported as unknown by `Lookup` (`Resolve` drops the flag). `CanonicalRepositoryURL` turns any remote into `https://<host>/<path>` 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)

Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <id> <url>...` | 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

Expand Down Expand Up @@ -199,6 +201,14 @@ For formatting details and platform notes, see [docs/CC_STATUSLINE.md](docs/CC_S

Besides tokens and cost, both tools then send your prompts, tool details (shell commands, file paths, truncated tool input or output, errors) and the assistant's responses. To keep some of these out, set `OTEL_LOG_USER_PROMPTS`, `OTEL_LOG_TOOL_DETAILS` or `OTEL_LOG_ASSISTANT_RESPONSES` to `0` in the `env` of `~/.claude/settings.json`, or `otel.log_user_prompt` / `otel.log_agent_responses` to `false` in `~/.codex/config.toml`. Re-running the install command resets them. `shelltime doctor` warns when a config written by an older version is missing newer keys, and `shelltime doctor --fix` re-runs the install.

## Projects

ShellTime groups your coding agent sessions into projects by the git repository they ran in, so a renamed or moved clone, a worktree or a subfolder stays one project. The repository comes from the folder's `origin` remote (else `upstream`, else the first remote), sent as `https://<host>/<path>` with any credentials in the remote URL removed. Claude Code reports it itself (`shelltime cc install` turns this on); for Codex and older Claude Code setups the daemon asks git about the session's folder. Sessions outside a repository, or in one without a remote, are grouped by machine and folder.

Sessions recorded before this were grouped by folder. A couple of minutes after it starts, the daemon moves this machine's folder projects whose folders still exist and are clones into their repository's project, once, and leaves `~/.shelltime/project-repositories.v1` behind. `shelltime cc projects` does the same by hand (`--dry-run` shows the folders and repositories without changing anything). Folders that no longer exist (renamed or deleted) can't be checked, and neither can a folder on a drive that isn't mounted, so run `shelltime cc projects` again once it is, and host names many machines share, like `localhost`, are skipped. A folder moves whole, into the repository it is a clone of today, so only folders where no session ever named a repository are moved this way: the server keys the others from the sessions that did, each session from the closest one before it.

To keep repository names to yourself, set `sendRepository: false` under `aiCodeOtel` in `~/.shelltime/config.yaml`. The daemon then never asks git, removes the repository Claude Code reports, and skips the migration; sessions are grouped by machine and folder. Restart the daemon (`shelltime daemon reinstall`) for a change to take effect.

## Codex Usage Tracking

ShellTime receives Codex data through two independent paths:
Expand Down
6 changes: 6 additions & 0 deletions cmd/daemon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,12 @@ func main() {
// (statusline mods, the desktop app, idle sessions).
processor.StartAnthropicUsageSync()

// Group the sessions recorded before repositories were named by repository, not folder.
// A cloud VM is no machine of the user's, and its home doesn't outlive the session.
if !aiCloudOnly {
go daemon.RunProjectMigrationOnce(ctx, cfg)
Comment thread
AnnatarHe marked this conversation as resolved.
Resolved
}

// Handle shutdown gracefully
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
Expand Down
5 changes: 5 additions & 0 deletions commands/aicode_backfill.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ func runAICodeBackfill(c *cli.Context, src aiCodeBackfillSource) error {
return nil
}

// The server groups sessions into projects by git repository when it knows it.
if cfg.SendsRepository() {
model.AttachBackfillRepositories(ctx, plan.upload, model.NewGitRepositoryResolver(time.Hour))
}

batches := model.PackBackfillBatches(src.clientType, plan.upload,
model.AICodeBackfillMaxEvents, model.AICodeBackfillMaxBatchBytes, model.AICodeBackfillMaxCompleted)
accepted := 0
Expand Down
107 changes: 107 additions & 0 deletions commands/aicode_projects.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package commands

import (
"errors"
"fmt"
"net/http"
"os"
"strconv"
"time"

"github.com/gookit/color"
"github.com/malamtime/cli/model"
"github.com/olekukonko/tablewriter"
"github.com/urfave/cli/v2"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)

// AICodeProjectsCommand is `shelltime cc projects` and `shelltime codex projects`: the projects
// of both agents are grouped together, so either runs the same migration.
var AICodeProjectsCommand = &cli.Command{
Name: "projects",
Usage: "Group this machine's coding agent projects by git repository instead of folder",
Comment thread
AnnatarHe marked this conversation as resolved.
Resolved
Description: "Sessions recorded before ShellTime named their git repository are grouped into projects by\n" +
"machine and folder, so a renamed or moved clone shows up as another project. This finds the\n" +
"repository of each such folder that still exists on this machine and moves its sessions into\n" +
"that repository's project. The daemon does this once on its own; run it again any time.",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "dry-run",
Usage: "show which folders would move without changing anything",
},
},
Action: commandAICodeProjects,
}

// aiCodeProjectsHosts names this machine for the migration; tests replace it.
var aiCodeProjectsHosts = func() []string {
return model.ProjectMigrationHosts(model.NewClaudeSettingsAICodeOtelEnvService().ResourceMachineName())
}

func commandAICodeProjects(c *cli.Context) error {
ctx, span := commandTracer.Start(c.Context, "aicode.projects", trace.WithSpanKind(trace.SpanKindClient))
defer span.End()
SetupLogger(os.ExpandEnv("$HOME/" + model.COMMAND_BASE_STORAGE_FOLDER))

cfg, err := configService.ReadConfigFile(ctx)
if err != nil {
return err
}
if cfg.Token == "" {
Comment thread
AnnatarHe marked this conversation as resolved.
Resolved
return errors.New("no ShellTime token configured, run `shelltime init` first")
}
if skippedInAICloudOnly(cfg, "Projects not grouped") {
return nil
}
if !cfg.SendsRepository() {
color.Yellow.Println("Projects not grouped: aiCodeOtel.sendRepository is off, so no repository is sent.")
return nil
}
endpoint := model.Endpoint{Token: cfg.Token, APIEndpoint: cfg.APIEndpoint}
hosts := aiCodeProjectsHosts()
if len(hosts) == 0 {
return errors.New("this machine's host name is one many machines share (like localhost), so its projects can't be told apart from theirs")
}
dryRun := c.Bool("dry-run")

color.Yellow.Println("Looking for projects grouped by folder...")
result, err := model.MigrateProjectRepositories(ctx, endpoint, hosts, model.NewGitRepositoryResolver(time.Hour), dryRun)
span.SetAttributes(attribute.Int("checked", result.Checked), attribute.Int("linked", len(result.Linked)))
if err != nil {
var statusErr *model.HTTPStatusError
if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusNotFound {
return errors.New("the ShellTime server can't group projects by repository yet, please try again after it is updated")
}
return fmt.Errorf("project migration failed: %w", err)
}

if result.Checked == 0 {
color.Green.Println("Every project of this machine is already grouped by repository.")
return nil
}
if len(result.Linked) > 0 {
w := tablewriter.NewWriter(os.Stdout)
w.Header([]string{"FOLDER", "REPOSITORY"})
for _, p := range result.Linked {
w.Append([]string{p.Pwd, p.Repository})
}
w.Render()
}

fmt.Printf("%d folder projects found: %d in a git repository, %d no longer here, %d not in a repository with a remote.\n",
result.Checked, len(result.Linked), result.Missing, result.NotRepositories)
if result.Unchecked > 0 {
color.Yellow.Printf("git didn't answer for %d folders; run it again to check them.\n", result.Unchecked)
}
if result.Truncated {
color.Yellow.Println("This machine has more folder projects than one run goes through; run it again to check the rest.")
}
switch {
case dryRun:
color.Green.Println("Dry run: nothing was changed.")
case len(result.Linked) > 0:
color.Green.Printf("Moved %s sessions into their repositories' projects.\n", strconv.Itoa(result.Sessions))
}
return nil
}
83 changes: 83 additions & 0 deletions commands/aicode_projects_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package commands

import (
"encoding/json"
"net/http"
"net/http/httptest"
"os/exec"
"testing"

"github.com/malamtime/cli/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"github.com/urfave/cli/v2"
)

func runProjects(t *testing.T, group string, token, endpoint string, args ...string) error {
t.Helper()
setupCCTest(t)
original := configService
mc := model.NewMockConfigService(t)
mc.On("ReadConfigFile", mock.Anything).Return(model.ShellTimeConfig{Token: token, APIEndpoint: endpoint}, nil).Maybe()
configService = mc
t.Cleanup(func() { configService = original })

// The machine's own host name may be a generic one (a CI runner's), which names nothing.
originalHosts := aiCodeProjectsHosts
aiCodeProjectsHosts = func() []string { return []string{"mbp"} }
t.Cleanup(func() { aiCodeProjectsHosts = originalHosts })

app := &cli.App{Name: "t", Commands: []*cli.Command{{Name: group, Subcommands: []*cli.Command{AICodeProjectsCommand}}}}
return app.Run(append([]string{"t", group, "projects"}, args...))
}

func TestAICodeProjectsMovesClones(t *testing.T) {
Comment thread
AnnatarHe marked this conversation as resolved.
Resolved
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git is not installed")
}
dir := t.TempDir()
for _, args := range [][]string{{"init", "-q"}, {"remote", "add", "origin", "https://github.com/acme/web.git"}} {
out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput()
require.NoError(t, err, string(out))
}

var moves int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/cc/projects/unresolved":
_ = json.NewEncoder(w).Encode(map[string]any{"projects": []map[string]any{{"host": "mbp", "pwd": dir, "sessions": 2}}})
case "/api/v1/cc/projects/repositories":
moves++
_ = json.NewEncoder(w).Encode(map[string]int{"updated": 2})
}
}))
t.Cleanup(server.Close)

require.NoError(t, runProjects(t, "codex", "tok", server.URL, "--dry-run"))
assert.Zero(t, moves)
require.NoError(t, runProjects(t, "cc", "tok", server.URL))
assert.Equal(t, 1, moves)
}

func TestAICodeProjectsSkippedInAICloudOnly(t *testing.T) {
t.Setenv("CLAUDE_CODE_REMOTE", "true")
var requests int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
}))
t.Cleanup(server.Close)

require.NoError(t, runProjects(t, "cc", "tok", server.URL))
assert.Zero(t, requests, "a cloud VM sends no host name or folders")
}

func TestAICodeProjectsErrors(t *testing.T) {
assert.ErrorContains(t, runProjects(t, "cc", "", "http://127.0.0.1:0"), "no ShellTime token")

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
t.Cleanup(server.Close)
assert.ErrorContains(t, runProjects(t, "cc", "tok", server.URL), "can't group projects by repository yet")
Comment thread
AnnatarHe marked this conversation as resolved.
Resolved
}
1 change: 1 addition & 0 deletions commands/cc.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ var CCCommand = &cli.Command{
CCStatuslineCommand,
CCBackfillCommand,
CCPullRequestCommand,
AICodeProjectsCommand,
},
}

Expand Down
1 change: 1 addition & 0 deletions commands/codex.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ var CodexCommand = &cli.Command{
CodexInstallCommand,
CodexUninstallCommand,
CodexBackfillCommand,
AICodeProjectsCommand,
},
}

Expand Down
Loading
Loading