From 93f5823cfe6c2dc54552b518a27fb2d72a283060 Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Sat, 5 Sep 2026 18:16:35 -0700 Subject: [PATCH 1/3] fix(cli): resolve Codex session identity for issue claims --- cmd/arc/main.go | 10 +- cmd/arc/prime.go | 5 +- cmd/arc/session.go | 17 +++ cmd/arc/session_test.go | 208 +++++++++++++++++++++++++++++++ internal/docs/WORKFLOWS.md | 21 ++++ tests/integration/update_test.go | 4 +- 6 files changed, 254 insertions(+), 11 deletions(-) create mode 100644 cmd/arc/session.go create mode 100644 cmd/arc/session_test.go diff --git a/cmd/arc/main.go b/cmd/arc/main.go index c38d1686..fedeb5c9 100644 --- a/cmd/arc/main.go +++ b/cmd/arc/main.go @@ -1058,12 +1058,10 @@ var updateCmd = &cobra.Command{ } if take { - // Resolve session ID: explicit flag > env var > error + sessionID = resolveSessionID(sessionID) if sessionID == "" { - sessionID = os.Getenv("ARC_SESSION_ID") - } - if sessionID == "" { - return errors.New("no session ID available — set ARC_SESSION_ID or pass --session-id") + return errors.New( + "no session ID available — set ARC_SESSION_ID or CODEX_THREAD_ID, or pass --session-id") } updates["ai_session_id"] = sessionID // Set status to in_progress unless user explicitly passed --status @@ -1131,7 +1129,7 @@ func init() { updateCmd.Flags().StringP("description", "d", "", "New description") updateCmd.Flags().Bool("stdin", false, "Read description from stdin") updateCmd.Flags().Bool("take", false, - "Take this issue for the current AI session (sets ai_session_id + status=in_progress)") + "Take this issue (session: --session-id > ARC_SESSION_ID > CODEX_THREAD_ID; status=in_progress)") updateCmd.Flags().String("session-id", "", "Explicit AI session ID (used with --take)") updateCmd.Flags().StringSlice("label-add", nil, "Label to add (repeatable)") updateCmd.Flags().StringSlice("label-remove", nil, "Label to remove (repeatable)") diff --git a/cmd/arc/prime.go b/cmd/arc/prime.go index 36971097..3016258e 100644 --- a/cmd/arc/prime.go +++ b/cmd/arc/prime.go @@ -53,10 +53,7 @@ Workflow customization: persistSessionID(sessionID) } - // Also check env var (may have been set by a previous SessionStart hook) - if sessionID == "" { - sessionID = os.Getenv("ARC_SESSION_ID") - } + sessionID = resolveSessionID(sessionID) // Check if this project has arc configured via workspace path resolution cwd, err := os.Getwd() diff --git a/cmd/arc/session.go b/cmd/arc/session.go new file mode 100644 index 00000000..bfe12035 --- /dev/null +++ b/cmd/arc/session.go @@ -0,0 +1,17 @@ +package main + +import "os" + +// resolveSessionID uses an explicit flag or hook identity first, then Arc's +// environment override, then the Codex thread identity. Codex SessionStart +// hooks register their session_id unchanged, matching CODEX_THREAD_ID in the +// session's commands. This only resolves identity; it does not register a session. +func resolveSessionID(explicit string) string { + if explicit != "" { + return explicit + } + if id := os.Getenv("ARC_SESSION_ID"); id != "" { + return id + } + return os.Getenv("CODEX_THREAD_ID") +} diff --git a/cmd/arc/session_test.go b/cmd/arc/session_test.go new file mode 100644 index 00000000..561e2e1f --- /dev/null +++ b/cmd/arc/session_test.go @@ -0,0 +1,208 @@ +package main + +import ( + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/sentiolabs/arc/internal/api" + "github.com/sentiolabs/arc/internal/client" + "github.com/sentiolabs/arc/internal/storage/sqlite" + "github.com/sentiolabs/arc/internal/types" + "github.com/spf13/cobra" + "github.com/stretchr/testify/require" +) + +// setupSessionTest isolates the server, database, config, cwd, and runtime env. +func setupSessionTest(t *testing.T) (*client.Client, string) { + t.Helper() + workDir := t.TempDir() + t.Chdir(workDir) + t.Setenv("ARC_SESSION_ID", "") + t.Setenv("CODEX_THREAD_ID", "") + t.Setenv("CLAUDE_ENV_FILE", "") + t.Setenv("ARC_TEAMMATE_ROLE", "") + + store, err := sqlite.New(filepath.Join(workDir, "test.db")) + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, store.Close()) }) + server := api.New(api.ServerOptions{Address: ":0", Store: store}) + ts := httptest.NewServer(server.Echo()) + t.Cleanup(ts.Close) + c := client.New(ts.URL) + proj, err := c.CreateProject("Session Test", "sess", "") + require.NoError(t, err) + _, err = c.CreateWorkspace(proj.ID, client.CreateWorkspaceRequest{Path: workDir}) + require.NoError(t, err) + + origURL, origConfig, origJSON := serverURL, configPath, outputJSON + serverURL, configPath, outputJSON = ts.URL, filepath.Join(workDir, "config.toml"), false + t.Cleanup(func() { serverURL, configPath, outputJSON = origURL, origConfig, origJSON }) + return c, proj.ID +} + +// sessionTestStdin supplies a hook payload without depending on the test runner's stdin. +func sessionTestStdin(t *testing.T, input string) { + t.Helper() + f, err := os.CreateTemp(t.TempDir(), "stdin") + require.NoError(t, err) + t.Cleanup(func() { require.NoError(t, f.Close()) }) + _, err = f.WriteString(input) + require.NoError(t, err) + _, err = f.Seek(0, 0) + require.NoError(t, err) + origStdin := os.Stdin + os.Stdin = f + t.Cleanup(func() { os.Stdin = origStdin }) +} + +// takeTestCommand uses fresh flags to avoid changing the package-global Cobra flags. +func takeTestCommand() *cobra.Command { + cmd := &cobra.Command{} + cmd.Flags().Bool("take", true, "") + cmd.Flags().String("session-id", "", "") + cmd.Flags().String("status", "", "") + return cmd +} + +func TestUpdateTakeSessionIdentity(t *testing.T) { + tests := []struct { + name, explicit, arcID, codexID, status, wantID, wantErr string + withoutTake bool + }{ + {name: "explicit", explicit: "explicit-session", wantID: "explicit-session"}, + {name: "arc environment", arcID: "arc-session", wantID: "arc-session"}, + {name: "codex", codexID: "codex-thread", wantID: "codex-thread"}, + {name: "missing", wantErr: "no session ID available"}, + {name: "flag wins conflicts", explicit: "flag", arcID: "arc-session", codexID: "codex", wantID: "flag"}, + {name: "arc wins conflict", arcID: "arc-session", codexID: "codex", wantID: "arc-session"}, + {name: "matching env", arcID: "same", codexID: "same", wantID: "same"}, + {name: "preserve status", codexID: "codex", status: string(types.StatusBlocked), wantID: "codex"}, + { + name: "flag requires take", explicit: "flag", codexID: "codex", withoutTake: true, + wantErr: "--session-id requires --take", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c, projID := setupSessionTest(t) + t.Setenv("ARC_SESSION_ID", tt.arcID) + t.Setenv("CODEX_THREAD_ID", tt.codexID) + issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: "Claim fixture"}) + require.NoError(t, err) + cmd := takeTestCommand() + if tt.withoutTake { + require.NoError(t, cmd.Flags().Set("take", "false")) + } + require.NoError(t, cmd.Flags().Set("session-id", tt.explicit)) + if tt.status != "" { + require.NoError(t, cmd.Flags().Set("status", tt.status)) + } + err = updateCmd.RunE(cmd, []string{issue.ID}) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + } else { + require.NoError(t, err) + } + got, err := c.GetIssueByID(issue.ID) + require.NoError(t, err) + require.Equal(t, tt.wantID, got.AISessionID) + switch { + case tt.wantErr != "": + require.Equal(t, types.StatusOpen, got.Status) + case tt.status != "": + require.Equal(t, types.Status(tt.status), got.Status) + default: + require.Equal(t, types.StatusInProgress, got.Status) + } + }) + } +} + +func TestCodexSessionRegistrationAndTake(t *testing.T) { + c, projID := setupSessionTest(t) + const threadID = "983a7cf7-bcb6-48fc-b485-129b4f1aaa45" + t.Setenv("CODEX_THREAD_ID", threadID) + cwd, err := os.Getwd() + require.NoError(t, err) + payload, err := json.Marshal(hookInput{SessionID: threadID, CWD: cwd}) + require.NoError(t, err) + sessionTestStdin(t, string(payload)) + require.NoError(t, runSessionStart(aiSessionStartCmd, true)) + registered, err := c.GetAISession(projID, threadID) + require.NoError(t, err) + issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: "Codex claim fixture"}) + require.NoError(t, err) + require.NoError(t, updateCmd.RunE(takeTestCommand(), []string{issue.ID})) + claimed, err := c.GetIssueByID(issue.ID) + require.NoError(t, err) + require.Equal(t, registered.ID, claimed.AISessionID) + require.Equal(t, types.StatusInProgress, claimed.Status) +} + +func TestSessionStartKeepsExplicitIdentity(t *testing.T) { + c, projID := setupSessionTest(t) + t.Setenv("ARC_SESSION_ID", "arc-env") + t.Setenv("CODEX_THREAD_ID", "codex-thread") + + // Runtime environment must not turn a missing hook identity into registration. + t.Run("missing hook identity", func(t *testing.T) { + sessionTestStdin(t, `{}`) + require.ErrorIs(t, runSessionStart(aiSessionStartCmd, true), errSkipSession) + }) + t.Run("missing manual identity", func(t *testing.T) { + require.EqualError(t, runSessionStart(&cobra.Command{}, false), "--id is required") + }) + sessions, err := c.ListAISessions(projID, 10, 0) + require.NoError(t, err) + require.Empty(t, sessions) + + // A supplied hook payload remains authoritative even when both env IDs differ. + cwd, err := os.Getwd() + require.NoError(t, err) + payload, err := json.Marshal(hookInput{SessionID: "hook-session", CWD: cwd}) + require.NoError(t, err) + sessionTestStdin(t, string(payload)) + require.NoError(t, runSessionStart(aiSessionStartCmd, true)) + sessions, err = c.ListAISessions(projID, 10, 0) + require.NoError(t, err) + require.Len(t, sessions, 1) + require.Equal(t, "hook-session", sessions[0].ID) +} + +func TestPrimeSessionIdentity(t *testing.T) { + const hookID = "983a7cf7-bcb6-48fc-b485-129b4f1aaa45" + tests := []struct{ name, hook, arcID, codexID, wantID string }{ + {name: "codex", codexID: "codex-thread", wantID: "codex-thread"}, + {name: "arc wins conflict", arcID: "arc-session", codexID: "codex-thread", wantID: "arc-session"}, + {name: "hook wins conflicts", hook: hookID, arcID: "arc-session", codexID: "codex-thread", wantID: hookID}, + {name: "missing"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + setupSessionTest(t) + t.Setenv("ARC_SESSION_ID", tt.arcID) + t.Setenv("CODEX_THREAD_ID", tt.codexID) + envFile := filepath.Join(t.TempDir(), "claude-env") + t.Setenv("CLAUDE_ENV_FILE", envFile) + payload, err := json.Marshal(hookInput{SessionID: tt.hook}) + require.NoError(t, err) + sessionTestStdin(t, string(payload)) + out := captureStdout(t, func() { primeCmd.Run(primeCmd, nil) }) + if tt.wantID == "" { + require.NotContains(t, out, "> **Session**:") + } else { + require.Contains(t, out, "> **Session**: `"+tt.wantID+"`") + } + if tt.hook == "" { + require.NoFileExists(t, envFile, "environment fallback must not be persisted as a hook identity") + } else { + data, err := os.ReadFile(envFile) + require.NoError(t, err) + require.Equal(t, "export ARC_SESSION_ID="+tt.hook+"\n", string(data)) + } + }) + } +} diff --git a/internal/docs/WORKFLOWS.md b/internal/docs/WORKFLOWS.md index 4d23d347..1cc845c7 100644 --- a/internal/docs/WORKFLOWS.md +++ b/internal/docs/WORKFLOWS.md @@ -39,6 +39,27 @@ Session Start (when arc is available): **Server connection**: Arc automatically connects to the server. If not running, start with `arc server` or let daemon auto-start. +### Claiming an issue for the current session + +`arc update --take` sets the issue's AI session and changes its status to +`in_progress` unless `--status` is supplied. Session identity uses the first +nonempty value in this order: + +1. `--session-id` (requires `--take`) +2. `ARC_SESSION_ID` +3. `CODEX_THREAD_ID`, provided by Codex for commands in the current thread + +Explicit flags and `ARC_SESSION_ID` take precedence when identities conflict. +Without any identity, the command fails without updating the issue. + +The Arc plugin's `SessionStart` hook registers the runtime's `session_id` +unchanged. In a Codex session this matches `CODEX_THREAD_ID`; no environment-file +repair is needed. `arc prime` uses the same environment fallback, while a valid +hook payload takes precedence and retains Claude's `CLAUDE_ENV_FILE` persistence. +Neither `prime` nor `--take` registers a session. Registration remains +`arc ai session start --stdin` for hooks or `arc ai session start --id --cwd ` +for manual use. + --- ## Compaction Survival {#compaction-survival} diff --git a/tests/integration/update_test.go b/tests/integration/update_test.go index 707c241d..9dfa3375 100644 --- a/tests/integration/update_test.go +++ b/tests/integration/update_test.go @@ -287,6 +287,8 @@ func TestUpdateTake(t *testing.T) { // TestUpdateTakeNoSession verifies that --take fails without a session ID. func TestUpdateTakeNoSession(t *testing.T) { + t.Setenv("ARC_SESSION_ID", "") + t.Setenv("CODEX_THREAD_ID", "") home := setupHome(t) arcCmdSuccess(t, home, "init", "take-nosess-proj", "--server", serverURL) @@ -297,7 +299,7 @@ func TestUpdateTakeNoSession(t *testing.T) { t.Fatalf("could not extract issue ID from create output: %s", createOut) } - // Should fail — no ARC_SESSION_ID and no --session-id + // Should fail with neither runtime identity nor --session-id. _, err := arcCmd(t, home, "update", id, "--take", "--server", serverURL) if err == nil { t.Error("expected error when --take used without session ID") From dfde76e2865b595f87d046e81bccb8f0e60a293c Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Sat, 5 Sep 2026 18:46:24 -0700 Subject: [PATCH 2/3] fix: register issue sessions across supported runtimes --- api/openapi.yaml | 18 +++ cmd/arc/main.go | 10 +- cmd/arc/prime.go | 9 +- cmd/arc/session.go | 70 +++++++-- cmd/arc/session_test.go | 171 ++++++++++++++++++--- internal/api/ai_sessions.go | 3 + internal/api/ai_sessions_test.go | 24 +++ internal/api/openapi.gen.go | 250 +++++++++++++++++-------------- internal/docs/WORKFLOWS.md | 47 ++++-- tests/integration/update_test.go | 1 + web/src/lib/api/types.ts | 27 ++++ 11 files changed, 466 insertions(+), 164 deletions(-) diff --git a/api/openapi.yaml b/api/openapi.yaml index 3c650001..7b27a1d3 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -665,6 +665,12 @@ paths: schema: $ref: "#/components/schemas/CreateAISessionRequest" responses: + "200": + description: Existing AI session in the same project (metadata preserved) + content: + application/json: + schema: + $ref: "#/components/schemas/AISessionResponse" "201": description: AI session created content: @@ -673,6 +679,18 @@ paths: $ref: "#/components/schemas/AISessionResponse" "400": $ref: "#/components/responses/BadRequest" + "409": + description: Session ID already belongs to another project + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + "422": + description: Working directory does not resolve to the requested project + content: + application/json: + schema: + $ref: "#/components/schemas/Error" "500": $ref: "#/components/responses/InternalError" diff --git a/cmd/arc/main.go b/cmd/arc/main.go index fedeb5c9..9aaf7471 100644 --- a/cmd/arc/main.go +++ b/cmd/arc/main.go @@ -1058,10 +1058,14 @@ var updateCmd = &cobra.Command{ } if take { - sessionID = resolveSessionID(sessionID) + sessionID, err = resolveClaimSessionID(c, args[0], sessionID) + if err != nil { + return err + } if sessionID == "" { return errors.New( - "no session ID available — set ARC_SESSION_ID or CODEX_THREAD_ID, or pass --session-id") + "no session ID available — set ARC_SESSION_ID, CODEX_THREAD_ID, or PI_SESSION_ID, " + + "or pass --session-id") } updates["ai_session_id"] = sessionID // Set status to in_progress unless user explicitly passed --status @@ -1129,7 +1133,7 @@ func init() { updateCmd.Flags().StringP("description", "d", "", "New description") updateCmd.Flags().Bool("stdin", false, "Read description from stdin") updateCmd.Flags().Bool("take", false, - "Take this issue (session: --session-id > ARC_SESSION_ID > CODEX_THREAD_ID; status=in_progress)") + "Take this issue (session: --session-id > ARC_SESSION_ID > runtime identity; status=in_progress)") updateCmd.Flags().String("session-id", "", "Explicit AI session ID (used with --take)") updateCmd.Flags().StringSlice("label-add", nil, "Label to add (repeatable)") updateCmd.Flags().StringSlice("label-remove", nil, "Label to remove (repeatable)") diff --git a/cmd/arc/prime.go b/cmd/arc/prime.go index 3016258e..3f65e8ef 100644 --- a/cmd/arc/prime.go +++ b/cmd/arc/prime.go @@ -31,8 +31,8 @@ var primeCmd = &cobra.Command{ Short: "Output AI-optimized workflow context", Long: `Output essential Arc workflow context in AI-optimized markdown format. -Designed for Claude Code hooks (SessionStart, PreCompact) and manual use -in Codex CLI to prevent agents from forgetting arc workflow after compaction. +Designed for Claude Code hooks (SessionStart, PreCompact), Codex, pi, and manual +use to prevent agents from forgetting Arc workflow after compaction. Modes: - Default: Full CLI reference (~1-2k tokens) @@ -53,7 +53,10 @@ Workflow customization: persistSessionID(sessionID) } - sessionID = resolveSessionID(sessionID) + sessionID, identityErr := resolveSessionID(sessionID) + if identityErr != nil { + _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "Warning:", identityErr) + } // Check if this project has arc configured via workspace path resolution cwd, err := os.Getwd() diff --git a/cmd/arc/session.go b/cmd/arc/session.go index bfe12035..b6471be4 100644 --- a/cmd/arc/session.go +++ b/cmd/arc/session.go @@ -1,17 +1,69 @@ package main -import "os" +import ( + "errors" + "fmt" + "os" -// resolveSessionID uses an explicit flag or hook identity first, then Arc's -// environment override, then the Codex thread identity. Codex SessionStart -// hooks register their session_id unchanged, matching CODEX_THREAD_ID in the -// session's commands. This only resolves identity; it does not register a session. -func resolveSessionID(explicit string) string { + "github.com/sentiolabs/arc/internal/client" + "github.com/sentiolabs/arc/internal/types" +) + +// resolveSessionID honors explicit and Arc identities before native fallbacks. +// Native IDs can be inherited across nested runtimes, so conflicting values +// need an explicit choice instead of silently attributing work to the wrong one. +func resolveSessionID(explicit string) (string, error) { if explicit != "" { - return explicit + return explicit, nil } if id := os.Getenv("ARC_SESSION_ID"); id != "" { - return id + return id, nil + } + codexID, piID := os.Getenv("CODEX_THREAD_ID"), os.Getenv("PI_SESSION_ID") + if codexID != "" && piID != "" && codexID != piID { + return "", errors.New("conflicting runtime session IDs: set ARC_SESSION_ID or pass --session-id") + } + if piID != "" { + return piID, nil + } + return codexID, nil +} + +// resolveClaimSessionID ensures the selected identity is registered in the +// issue's project before updating ownership, regardless of the runtime or hook. +func resolveClaimSessionID(c *client.Client, issueID, explicit string) (string, error) { + id, err := resolveSessionID(explicit) + if err != nil || id == "" { + return id, err + } + + issue, err := c.GetIssueByID(issueID) + if err != nil { + return "", fmt.Errorf("register AI session: resolve issue: %w", err) + } + // Reuse an existing hook registration without changing its metadata. A + // worker may be executing from a different cwd than its registered parent. + if existing, err := c.GetAISession(issue.ProjectID, id); err == nil { + return validateClaimSession(&existing.AISession, id, issue.ProjectID) + } + cwd, err := os.Getwd() + if err != nil { + return "", fmt.Errorf("register AI session: working directory: %w", err) + } + // The issue's project is authoritative. The server validates the actual cwd + // and preserves existing session metadata on an idempotent registration. + session, err := c.CreateAISession(issue.ProjectID, &types.AISession{ID: id, CWD: cwd}) + if err != nil { + return "", fmt.Errorf("register AI session: %w", err) + } + return validateClaimSession(session, id, issue.ProjectID) +} + +func validateClaimSession(session *types.AISession, id, projectID string) (string, error) { + // Older servers can return a same-ID session from a different project. + if session == nil || session.ID != id || session.ProjectID != projectID { + return "", fmt.Errorf("register AI session: response does not match session %q and issue project %q", + id, projectID) } - return os.Getenv("CODEX_THREAD_ID") + return id, nil } diff --git a/cmd/arc/session_test.go b/cmd/arc/session_test.go index 561e2e1f..d186d831 100644 --- a/cmd/arc/session_test.go +++ b/cmd/arc/session_test.go @@ -2,9 +2,12 @@ package main import ( "encoding/json" + "net/http" "net/http/httptest" "os" "path/filepath" + "strings" + "sync/atomic" "testing" "github.com/sentiolabs/arc/internal/api" @@ -22,6 +25,7 @@ func setupSessionTest(t *testing.T) (*client.Client, string) { t.Chdir(workDir) t.Setenv("ARC_SESSION_ID", "") t.Setenv("CODEX_THREAD_ID", "") + t.Setenv("PI_SESSION_ID", "") t.Setenv("CLAUDE_ENV_FILE", "") t.Setenv("ARC_TEAMMATE_ROLE", "") @@ -69,12 +73,20 @@ func takeTestCommand() *cobra.Command { func TestUpdateTakeSessionIdentity(t *testing.T) { tests := []struct { - name, explicit, arcID, codexID, status, wantID, wantErr string - withoutTake bool + name, explicit, arcID, codexID, piID, status, wantID, wantErr string + withoutTake bool }{ {name: "explicit", explicit: "explicit-session", wantID: "explicit-session"}, {name: "arc environment", arcID: "arc-session", wantID: "arc-session"}, {name: "codex", codexID: "codex-thread", wantID: "codex-thread"}, + {name: "pi", piID: "pi-session", wantID: "pi-session"}, + {name: "native conflict", codexID: "codex", piID: "pi", wantErr: "conflicting runtime session IDs"}, + {name: "same native identity", codexID: "same", piID: "same", wantID: "same"}, + {name: "flag resolves native conflict", explicit: "flag", codexID: "codex", piID: "pi", wantID: "flag"}, + { + name: "arc resolves native conflict", arcID: "arc-session", + codexID: "codex", piID: "pi", wantID: "arc-session", + }, {name: "missing", wantErr: "no session ID available"}, {name: "flag wins conflicts", explicit: "flag", arcID: "arc-session", codexID: "codex", wantID: "flag"}, {name: "arc wins conflict", arcID: "arc-session", codexID: "codex", wantID: "arc-session"}, @@ -90,6 +102,7 @@ func TestUpdateTakeSessionIdentity(t *testing.T) { c, projID := setupSessionTest(t) t.Setenv("ARC_SESSION_ID", tt.arcID) t.Setenv("CODEX_THREAD_ID", tt.codexID) + t.Setenv("PI_SESSION_ID", tt.piID) issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: "Claim fixture"}) require.NoError(t, err) cmd := takeTestCommand() @@ -117,29 +130,139 @@ func TestUpdateTakeSessionIdentity(t *testing.T) { default: require.Equal(t, types.StatusInProgress, got.Status) } + sessions, err := c.ListAISessions(projID, 10, 0) + require.NoError(t, err) + if tt.wantErr == "" { + require.Len(t, sessions, 1, "every claim must have a registered session") + require.Equal(t, tt.wantID, sessions[0].ID) + } else { + require.Empty(t, sessions) + } }) } } -func TestCodexSessionRegistrationAndTake(t *testing.T) { - c, projID := setupSessionTest(t) - const threadID = "983a7cf7-bcb6-48fc-b485-129b4f1aaa45" - t.Setenv("CODEX_THREAD_ID", threadID) - cwd, err := os.Getwd() - require.NoError(t, err) - payload, err := json.Marshal(hookInput{SessionID: threadID, CWD: cwd}) - require.NoError(t, err) - sessionTestStdin(t, string(payload)) - require.NoError(t, runSessionStart(aiSessionStartCmd, true)) - registered, err := c.GetAISession(projID, threadID) - require.NoError(t, err) - issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: "Codex claim fixture"}) - require.NoError(t, err) - require.NoError(t, updateCmd.RunE(takeTestCommand(), []string{issue.ID})) - claimed, err := c.GetIssueByID(issue.ID) - require.NoError(t, err) - require.Equal(t, registered.ID, claimed.AISessionID) - require.Equal(t, types.StatusInProgress, claimed.Status) +func TestRuntimeHookRegistrationAndTake(t *testing.T) { + for _, runtime := range []string{"claude", "codex", "pi"} { + t.Run(runtime, func(t *testing.T) { + c, projID := setupSessionTest(t) + const threadID = "983a7cf7-bcb6-48fc-b485-129b4f1aaa45" + switch runtime { + case "claude": + envFile := filepath.Join(t.TempDir(), "claude-env") + t.Setenv("CLAUDE_ENV_FILE", envFile) + sessionTestStdin(t, `{"session_id":"`+threadID+`"}`) + captureStdout(t, func() { primeCmd.Run(primeCmd, nil) }) + data, err := os.ReadFile(envFile) + require.NoError(t, err) + require.Equal(t, "export ARC_SESSION_ID="+threadID+"\n", string(data)) + t.Setenv("ARC_SESSION_ID", threadID) + case "codex": + t.Setenv("CODEX_THREAD_ID", threadID) + case "pi": + t.Setenv("PI_SESSION_ID", threadID) + } + cwd, err := os.Getwd() + require.NoError(t, err) + payload, err := json.Marshal(hookInput{ + SessionID: threadID, CWD: cwd, TranscriptPath: "/recorded/transcript.jsonl", + }) + require.NoError(t, err) + sessionTestStdin(t, string(payload)) + require.NoError(t, runSessionStart(aiSessionStartCmd, true)) + registered, err := c.GetAISession(projID, threadID) + require.NoError(t, err) + issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: "Runtime claim fixture"}) + require.NoError(t, err) + // A registered parent remains usable from a worker's different directory. + t.Chdir(t.TempDir()) + require.NoError(t, updateCmd.RunE(takeTestCommand(), []string{issue.ID})) + claimed, err := c.GetIssueByID(issue.ID) + require.NoError(t, err) + require.Equal(t, registered.ID, claimed.AISessionID) + require.Equal(t, types.StatusInProgress, claimed.Status) + require.NoError(t, updateCmd.RunE(takeTestCommand(), []string{issue.ID})) + retried, err := c.GetAISession(projID, threadID) + require.NoError(t, err) + require.Equal(t, registered.AISession, retried.AISession, "claims must retain original hook metadata") + }) + } +} + +func TestClaimRejectsProjectMismatch(t *testing.T) { + for _, mismatch := range []string{"cwd", "registered session"} { + t.Run(mismatch, func(t *testing.T) { + c, projID := setupSessionTest(t) + other, err := c.CreateProject("Other Project", "other", "") + require.NoError(t, err) + t.Setenv("CODEX_THREAD_ID", "worker-thread") + targetProject := projID + if mismatch == "cwd" { + targetProject = other.ID + } else { + _, err = c.CreateAISession(other.ID, &types.AISession{ID: "worker-thread"}) + require.NoError(t, err) + } + issue, err := c.CreateIssue(targetProject, client.CreateIssueRequest{Title: "Must remain unclaimed"}) + require.NoError(t, err) + err = updateCmd.RunE(takeTestCommand(), []string{issue.ID}) + require.ErrorContains(t, err, "register AI session") + got, err := c.GetIssueByID(issue.ID) + require.NoError(t, err) + require.Empty(t, got.AISessionID) + require.Equal(t, types.StatusOpen, got.Status) + }) + } +} + +func TestClaimValidatesRegistrationResponse(t *testing.T) { + for _, failure := range []string{"wrong project", "wrong id", "server error"} { + t.Run(failure, func(t *testing.T) { + t.Setenv("ARC_SESSION_ID", "") + t.Setenv("CODEX_THREAD_ID", "worker-thread") + t.Setenv("PI_SESSION_ID", "") + var updated atomic.Bool + ts := claimRegistrationFailureServer(failure, &updated) + t.Cleanup(ts.Close) + origURL, origConfig := serverURL, configPath + serverURL, configPath = ts.URL, filepath.Join(t.TempDir(), "config.toml") + t.Cleanup(func() { serverURL, configPath = origURL, origConfig }) + err := updateCmd.RunE(takeTestCommand(), []string{"fixture"}) + require.ErrorContains(t, err, "register AI session") + require.False(t, updated.Load(), "registration failure must stop before issue mutation") + }) + } +} + +func claimRegistrationFailureServer(failure string, updated *atomic.Bool) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.Method { + case http.MethodGet: + if strings.Contains(r.URL.Path, "/ai/sessions/") { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error":"not found"}`)) + return + } + _ = json.NewEncoder(w).Encode(types.Issue{ID: "fixture", ProjectID: "target-project"}) + case http.MethodPost: + if failure == "server error" { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"error":"registration unavailable"}`)) + return + } + session := types.AISession{ID: "worker-thread", ProjectID: "target-project"} + if failure == "wrong project" { + session.ProjectID = "other-project" + } else { + session.ID = "other-thread" + } + _ = json.NewEncoder(w).Encode(session) + case http.MethodPut: + updated.Store(true) + _ = json.NewEncoder(w).Encode(types.Issue{ID: "fixture"}) + } + })) } func TestSessionStartKeepsExplicitIdentity(t *testing.T) { @@ -174,8 +297,11 @@ func TestSessionStartKeepsExplicitIdentity(t *testing.T) { func TestPrimeSessionIdentity(t *testing.T) { const hookID = "983a7cf7-bcb6-48fc-b485-129b4f1aaa45" - tests := []struct{ name, hook, arcID, codexID, wantID string }{ + tests := []struct{ name, hook, arcID, codexID, piID, wantID string }{ {name: "codex", codexID: "codex-thread", wantID: "codex-thread"}, + {name: "pi", piID: "pi-session", wantID: "pi-session"}, + {name: "native conflict", codexID: "codex", piID: "pi"}, + {name: "hook resolves native conflict", hook: hookID, codexID: "codex", piID: "pi", wantID: hookID}, {name: "arc wins conflict", arcID: "arc-session", codexID: "codex-thread", wantID: "arc-session"}, {name: "hook wins conflicts", hook: hookID, arcID: "arc-session", codexID: "codex-thread", wantID: hookID}, {name: "missing"}, @@ -185,6 +311,7 @@ func TestPrimeSessionIdentity(t *testing.T) { setupSessionTest(t) t.Setenv("ARC_SESSION_ID", tt.arcID) t.Setenv("CODEX_THREAD_ID", tt.codexID) + t.Setenv("PI_SESSION_ID", tt.piID) envFile := filepath.Join(t.TempDir(), "claude-env") t.Setenv("CLAUDE_ENV_FILE", envFile) payload, err := json.Marshal(hookInput{SessionID: tt.hook}) diff --git a/internal/api/ai_sessions.go b/internal/api/ai_sessions.go index e065809c..e79dca3e 100644 --- a/internal/api/ai_sessions.go +++ b/internal/api/ai_sessions.go @@ -100,6 +100,9 @@ func (s *Server) createAISession(c echo.Context) error { if getErr != nil { return errorJSON(c, http.StatusInternalServerError, err.Error()) } + if existing.ProjectID != projectID { + return errorJSON(c, http.StatusConflict, "session ID already belongs to another project") + } return successJSON(c, existing) } diff --git a/internal/api/ai_sessions_test.go b/internal/api/ai_sessions_test.go index 95174868..a2ebe25c 100644 --- a/internal/api/ai_sessions_test.go +++ b/internal/api/ai_sessions_test.go @@ -336,6 +336,30 @@ func TestCreateAISession_Idempotent(t *testing.T) { } } +func TestCreateAISession_DuplicateIDInAnotherProject(t *testing.T) { + server, cleanup := testServer(t) + defer cleanup() + e := server.echo + projectA := createNamedProject(t, e, "session-owner", "own") + projectB := createNamedProject(t, e, "session-collision", "col") + createTestAISession(t, e, aiSessionOpts{ + ProjectID: projectA, ID: "same-session", TranscriptPath: "/private/transcript.jsonl", + }) + + req := httptest.NewRequest(http.MethodPost, sessionURL(projectB, ""), + strings.NewReader(`{"id":"same-session"}`)) + req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON) + rec := httptest.NewRecorder() + e.ServeHTTP(rec, req) + if rec.Code != http.StatusConflict { + t.Fatalf("expected conflict, got %d: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.String() + if strings.Contains(body, "/private/transcript.jsonl") || strings.Contains(body, projectA) { + t.Fatal("cross-project duplicate response disclosed the existing session") + } +} + func TestGetAISession(t *testing.T) { server, cleanup := testServer(t) defer cleanup() diff --git a/internal/api/openapi.gen.go b/internal/api/openapi.gen.go index 048dd783..04c85009 100644 --- a/internal/api/openapi.gen.go +++ b/internal/api/openapi.gen.go @@ -3385,6 +3385,15 @@ type CreateAISessionResponseObject interface { VisitCreateAISessionResponse(w http.ResponseWriter) error } +type CreateAISession200JSONResponse AISessionResponse + +func (response CreateAISession200JSONResponse) VisitCreateAISessionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + + return json.NewEncoder(w).Encode(response) +} + type CreateAISession201JSONResponse AISessionResponse func (response CreateAISession201JSONResponse) VisitCreateAISessionResponse(w http.ResponseWriter) error { @@ -3403,6 +3412,24 @@ func (response CreateAISession400JSONResponse) VisitCreateAISessionResponse(w ht return json.NewEncoder(w).Encode(response) } +type CreateAISession409JSONResponse Error + +func (response CreateAISession409JSONResponse) VisitCreateAISessionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(409) + + return json.NewEncoder(w).Encode(response) +} + +type CreateAISession422JSONResponse Error + +func (response CreateAISession422JSONResponse) VisitCreateAISessionResponse(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(422) + + return json.NewEncoder(w).Encode(response) +} + type CreateAISession500JSONResponse struct{ InternalErrorJSONResponse } func (response CreateAISession500JSONResponse) VisitCreateAISessionResponse(w http.ResponseWriter) error { @@ -6366,117 +6393,118 @@ func (sh *strictHandler) GetTeamContext(ctx echo.Context, projectID ProjectID, p // Base64 encoded, gzipped, json marshaled Sw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BAcsQqbttf5dK4s4ZaKmhTqXNNIsYHkUcmFcoI3Y5UZKlWMJlT+8DNvLavtW", + "qDV5IyxbR1GRJ2uCFNIN5dojt327ZK8p18Y6cUr6hGrFeNr8dqzW9coHPap6y+xe9L32yQxz761gQIFa", + "AlDN2b5bXyQNEw0lxKtoykDiJvKcJdCgtgVbTDhofb2OQFnZtVX7jRmb226eni+DEDgyu2vH43/hlCTa", + "oSyjDnU8aFPVHMokIWogTt/XbY6WPXuw+5DaCYMgaT4vXf4WKTTY49+iix6ye/6FPep66NF6IsHASo//", + "2sUVpb/awhfbdWl6fZm651F/2YKO9BikdEIdZ9aL008U0g7Nb1ldqZ1M3QYEJpMujry4QjFLFLkctJ8+", + "hZG9cowbz+GbiW1OtEIIDDDadojfoXdkXA51GAnjRNpoiCZgdP7dKMrwN5IVWXT+chRlhJq/z0ImRnWg", + "OpWsGaWITGSqYczwt3dA54rOr87O+shmXmunk3aB2o8SS1vMrz7Em1h8n9OkR7UD9z7FtM/TxTS2JmIX", + "Hr2ZLswLOkBUxrQb8KeEwsSEndRzWqQpnioCmDxCj+3vZu7eWuue1IGctBgeKytVQzvWMtGGDj++Qxe6", + "8EuPInT0XglSE5GneIn005HPui8CrDuKwuLrl9yYGwgLwWKiI42VHLfGU0Bfwox8a89WITtgBazREJYt", + "Zw8hvQpQBA7UI7wW947xWQMncSUK0yLj2ryZp4dcPI8lGH3pdVyq+f/Ccb5oizQBjV2QxNnZw6AOefRu", + "SrmZCYNRKAtwbbHu/X+01ACqFIcNIqgZcm2kncQLkpq8ZopNDCUhIma3wCE5mXGWefNXNO4y6ZsHRI9G", + "GQiB5/12gZkktKu3t2GfXqeagy59FQbYiLsPt76D0JmYVCOdbt9MlIDC3eQWpwUEn7I0aX3aExTwdjWy", + "yOw9YNX+PN6y75ReYpU1msQLTOf6B0sT83fKjG/CgeVAIfE4O15OcJKs/sQhY7f6Rx0eLYeYf7mnIZYt", + "430bMBxdxvcyxUUC6JIl4Nnw4ayv2uqk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9xTsa3L7TRbYFo68ZcXaHtm1NlP/Fw", + "nfDl9ac3Oj2TkhnEyzgFVDK4qOYpdVVTDCh1o3XN1wIK0HM1PvC1sxgt0waKFzsNbaUW6m3z90IvlheP", + "NlC9ekdx8PXyG9z7tgt8qjvIwcVT6znm4OKm74R/RNQ8mu00P6rjW9njmu86P8jXUOhJ2VSxF56S1JhH", + "5bc+J16X1tWZ3tbulHNXQGAuyQzH/p5Mz/2HLw//HwAA//9RCR88wcEAAA==", } // GetSwagger returns the content of the embedded swagger specification file diff --git a/internal/docs/WORKFLOWS.md b/internal/docs/WORKFLOWS.md index 1cc845c7..9dfcd02b 100644 --- a/internal/docs/WORKFLOWS.md +++ b/internal/docs/WORKFLOWS.md @@ -41,24 +41,39 @@ Session Start (when arc is available): ### Claiming an issue for the current session -`arc update --take` sets the issue's AI session and changes its status to -`in_progress` unless `--status` is supplied. Session identity uses the first -nonempty value in this order: +`arc update --take` registers or reuses the issue's AI session and changes +its status to `in_progress` unless `--status` is supplied. Session identity uses: 1. `--session-id` (requires `--take`) -2. `ARC_SESSION_ID` -3. `CODEX_THREAD_ID`, provided by Codex for commands in the current thread - -Explicit flags and `ARC_SESSION_ID` take precedence when identities conflict. -Without any identity, the command fails without updating the issue. - -The Arc plugin's `SessionStart` hook registers the runtime's `session_id` -unchanged. In a Codex session this matches `CODEX_THREAD_ID`; no environment-file -repair is needed. `arc prime` uses the same environment fallback, while a valid -hook payload takes precedence and retains Claude's `CLAUDE_ENV_FILE` persistence. -Neither `prime` nor `--take` registers a session. Registration remains -`arc ai session start --stdin` for hooks or `arc ai session start --id --cwd ` -for manual use. +2. `ARC_SESSION_ID`, the runtime-neutral override +3. `CODEX_THREAD_ID` or `PI_SESSION_ID`, provided by their respective runtimes + +Explicit flags and `ARC_SESSION_ID` take precedence. If both native variables +are nonempty and differ, the command fails: choose the current identity with +`ARC_SESSION_ID` or `--session-id`. This prevents a nested runtime from silently +claiming work as an inherited parent. Missing identity also leaves the issue unchanged. + +Claude Code's Arc hooks register the supplied `session_id` and persist it through +`CLAUDE_ENV_FILE` as `ARC_SESSION_ID`. Claude subagent IDs are separate agent records; +they are not substituted for the parent session ID. Codex uses its exact thread ID, +including spawned workers. Pi uses its session manager's exact ID; its adapter +should send `session_id`, `cwd`, and `transcript_path` to +`arc ai session start --stdin` and bind extension commands to the current session. +No runtime's session identity is inferred from an agent ID or transcript filename. + +Every `--take` verifies that the selected session exists in the issue's project. +Existing hook metadata is preserved, even if the command runs from another cwd. +If registration is missing, Arc registers the exact ID using the current cwd, +which the server validates against that project. No transcript path is invented. +Registration errors or a session belonging to another project stop the claim before +updating the issue. This also applies to explicit and `ARC_SESSION_ID` identities, +which previously could assign an unregistered ID. Register them first from the +correct workspace when claiming from elsewhere. + +`arc prime` displays identity without registering it. A valid hook payload takes +precedence and retains Claude's environment-file persistence. Conflicting native +IDs produce a warning and omit the session line; workflow context still prints. +Manual registration uses `arc ai session start --id --cwd `. --- diff --git a/tests/integration/update_test.go b/tests/integration/update_test.go index 9dfa3375..a334a4d9 100644 --- a/tests/integration/update_test.go +++ b/tests/integration/update_test.go @@ -289,6 +289,7 @@ func TestUpdateTake(t *testing.T) { func TestUpdateTakeNoSession(t *testing.T) { t.Setenv("ARC_SESSION_ID", "") t.Setenv("CODEX_THREAD_ID", "") + t.Setenv("PI_SESSION_ID", "") home := setupHome(t) arcCmdSuccess(t, home, "init", "take-nosess-proj", "--server", serverURL) diff --git a/web/src/lib/api/types.ts b/web/src/lib/api/types.ts index c6d278ff..6c81e7dd 100644 --- a/web/src/lib/api/types.ts +++ b/web/src/lib/api/types.ts @@ -1864,6 +1864,15 @@ export interface operations { }; }; responses: { + /** @description Existing AI session in the same project (metadata preserved) */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AISessionResponse"]; + }; + }; /** @description AI session created */ 201: { headers: { @@ -1874,6 +1883,24 @@ export interface operations { }; }; 400: components["responses"]["BadRequest"]; + /** @description Session ID already belongs to another project */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Working directory does not resolve to the requested project */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; 500: components["responses"]["InternalError"]; }; }; From 16731f9b6833700f07a2e9d58fbf4d8cee4fa726 Mon Sep 17 00:00:00 2001 From: Ben Firestone Date: Sat, 5 Sep 2026 20:10:07 -0700 Subject: [PATCH 3/3] fix(cli): require explicit session bindings --- cmd/arc/main.go | 14 ++-- cmd/arc/prime.go | 52 ++++++++++---- cmd/arc/prime_test.go | 13 ++++ cmd/arc/session.go | 38 +++++++--- cmd/arc/session_test.go | 138 +++++++++++++++++++++++++++---------- internal/docs/WORKFLOWS.md | 36 ++++++++-- 6 files changed, 218 insertions(+), 73 deletions(-) diff --git a/cmd/arc/main.go b/cmd/arc/main.go index fedeb5c9..4cb2cddd 100644 --- a/cmd/arc/main.go +++ b/cmd/arc/main.go @@ -1052,16 +1052,20 @@ var updateCmd = &cobra.Command{ // Handle --take flag take, _ := cmd.Flags().GetBool("take") sessionID, _ := cmd.Flags().GetString("session-id") + sessionIDSet := cmd.Flags().Changed("session-id") - if sessionID != "" && !take { + if sessionIDSet && !take { return errors.New("--session-id requires --take") } if take { - sessionID = resolveSessionID(sessionID) + sessionID, err = resolveSessionID(sessionID, sessionIDSet) + if err != nil { + return err + } if sessionID == "" { return errors.New( - "no session ID available — set ARC_SESSION_ID or CODEX_THREAD_ID, or pass --session-id") + "no session ID available — set ARC_SESSION_ID or pass --session-id") } updates["ai_session_id"] = sessionID // Set status to in_progress unless user explicitly passed --status @@ -1129,8 +1133,8 @@ func init() { updateCmd.Flags().StringP("description", "d", "", "New description") updateCmd.Flags().Bool("stdin", false, "Read description from stdin") updateCmd.Flags().Bool("take", false, - "Take this issue (session: --session-id > ARC_SESSION_ID > CODEX_THREAD_ID; status=in_progress)") - updateCmd.Flags().String("session-id", "", "Explicit AI session ID (used with --take)") + "Take this issue (session: --session-id > ARC_SESSION_ID; status=in_progress)") + updateCmd.Flags().String("session-id", "", "Explicit AI session ID (requires --take; overrides ARC_SESSION_ID)") updateCmd.Flags().StringSlice("label-add", nil, "Label to add (repeatable)") updateCmd.Flags().StringSlice("label-remove", nil, "Label to remove (repeatable)") } diff --git a/cmd/arc/prime.go b/cmd/arc/prime.go index 3016258e..f10e7107 100644 --- a/cmd/arc/prime.go +++ b/cmd/arc/prime.go @@ -46,19 +46,28 @@ Role detection (in priority order): Workflow customization: - Place a .arc/PRIME.md file to override the default output entirely.`, - Run: func(cmd *cobra.Command, args []string) { + RunE: func(cmd *cobra.Command, args []string) error { + explicitSessionID, _ := cmd.Flags().GetString("session-id") + explicitSessionIDSet := cmd.Flags().Changed("session-id") + if explicitSessionIDSet && explicitSessionID == "" { + return errEmptySessionID + } + // Read hook stdin and persist session ID if available - sessionID := readHookStdin() - if sessionID != "" { - persistSessionID(sessionID) + hookSessionID := readHookStdin() + if hookSessionID != "" { + persistSessionID(hookSessionID) } - sessionID = resolveSessionID(sessionID) + sessionID, err := resolvePrimeSessionID(explicitSessionID, explicitSessionIDSet, hookSessionID) + if err != nil { + return err + } // Check if this project has arc configured via workspace path resolution cwd, err := os.Getwd() if err != nil { - os.Exit(0) + return nil } normalizedCwd := project.NormalizePath(cwd) @@ -74,7 +83,7 @@ Workflow customization: // Fall back to legacy config check (works offline) arcHome := project.DefaultArcHome() if cfg, err := readLegacyConfig(arcHome, cwd); err != nil || cfg == nil { - os.Exit(0) + return nil } } @@ -82,7 +91,7 @@ Workflow customization: localPrimePath := ".arc/PRIME.md" if content, err := os.ReadFile(localPrimePath); err == nil { _, _ = os.Stdout.Write(content) - return + return nil } // Detect role from flag or env var @@ -94,14 +103,14 @@ Workflow customization: // Role-based output takes precedence over mode flags if role == "lead" { if err := outputTeamLeadContext(os.Stdout, sessionID); err != nil { - os.Exit(0) + return nil } - return + return nil } else if role != "" { if err := outputTeammateContext(os.Stdout, role, sessionID); err != nil { - os.Exit(0) + return nil } - return + return nil } // Determine output mode @@ -112,8 +121,9 @@ Workflow customization: // Output workflow context if err := outputPrimeContext(os.Stdout, mcpMode, sessionID); err != nil { - os.Exit(0) + return nil } + return nil }, } @@ -222,6 +232,7 @@ func init() { primeCmd.Flags().BoolVar(&primeFullMode, "full", false, "Force full CLI output") primeCmd.Flags().BoolVar(&primeMCPMode, "mcp", false, "Force MCP mode (minimal output)") primeCmd.Flags().StringVar(&primeRole, "role", "", "Teammate role (lead, frontend, backend, etc.)") + primeCmd.Flags().String("session-id", "", "Explicit AI session ID (overrides hook input and ARC_SESSION_ID)") rootCmd.AddCommand(primeCmd) } @@ -336,6 +347,16 @@ var tmplCLI = template.Must(template.New("cli").Parse(`# Arc Workflow Context - Git workflow: commit and push at session end - Session management: check ` + "`arc ready`" + ` for available work +### Session Identity +- The CLI accepts only ` + "`--session-id`" + ` and ` + "`ARC_SESSION_ID`" + `; harnesses pass their + current identity explicitly. +- Pass a harness's current binding as + ` + "`arc update --take --session-id `" + ` or + ` + "`arc prime --session-id `" + `. Do not copy a parent session ID into a spawned worker. +- A supplied empty ` + "`--session-id`" + ` fails instead of falling back. + ` + "`--session-id`" + ` on ` + "`update`" + ` requires ` + "`--take`" + `. +- ` + "`prime`" + ` and ` + "`--take`" + ` do not register sessions; harness setup owns registration. + ## Essential Commands ### Finding Work @@ -366,7 +387,8 @@ var tmplCLI = template.Must(template.New("cli").Parse(`# Arc Workflow Context ` + "`arc create \"Phase\" --type=milestone --parent=`" + ` (auto-sequences after the previous milestone; ` + "`--parallel`" + ` for an independent track, ` + "`--after=`" + ` to sequence explicitly) -- ` + "`arc update --take`" + ` - Take issue for current AI session (sets session ID + in_progress) +- ` + "`arc update --take --session-id `" + ` - Take issue for current AI session + (sets session ID + in_progress) - ` + "`arc update --title=\"new title\"`" + ` - Update fields - ` + "`arc update --stdin <<'EOF'`" + ` - Update description via stdin heredoc - ` + "`arc close `" + ` - Mark complete @@ -401,7 +423,7 @@ var tmplCLI = template.Must(template.New("cli").Parse(`# Arc Workflow Context ` + "```bash" + ` arc ready # Find available work arc show # Review issue details -arc update --take # Take it (sets session ID + in_progress) +arc update --take --session-id # Take it (sets session ID + in_progress) ` + "```" + ` **Completing work:** diff --git a/cmd/arc/prime_test.go b/cmd/arc/prime_test.go index 118eb02a..e89e362b 100644 --- a/cmd/arc/prime_test.go +++ b/cmd/arc/prime_test.go @@ -78,6 +78,9 @@ func TestPrime(t *testing.T) { {"documents arc roadmap command", "arc roadmap"}, {"documents --under flag", "--under"}, {"documents --parallel flag", "--parallel"}, + {"documents generic session identity", "ARC_SESSION_ID"}, + {"documents explicit session identity", "--session-id"}, + {"documents separate registration", "do not register sessions"}, } for _, tt := range tests { @@ -87,4 +90,14 @@ func TestPrime(t *testing.T) { } }) } + if strings.Contains(content, "$CURRENT_SESSION_ID") { + t.Error("prime output must not invent a session environment variable") + } +} + +func TestPrimeSessionIDFlag(t *testing.T) { + flag := primeCmd.Flags().Lookup("session-id") + if flag == nil { + t.Fatal("prime must expose --session-id") + } } diff --git a/cmd/arc/session.go b/cmd/arc/session.go index bfe12035..b72e3b7e 100644 --- a/cmd/arc/session.go +++ b/cmd/arc/session.go @@ -1,17 +1,33 @@ package main -import "os" +import ( + "errors" + "os" +) -// resolveSessionID uses an explicit flag or hook identity first, then Arc's -// environment override, then the Codex thread identity. Codex SessionStart -// hooks register their session_id unchanged, matching CODEX_THREAD_ID in the -// session's commands. This only resolves identity; it does not register a session. -func resolveSessionID(explicit string) string { - if explicit != "" { - return explicit +var errEmptySessionID = errors.New("--session-id cannot be empty") + +// resolveSessionID uses an explicitly supplied session ID or Arc's generic +// environment fallback. Harness integrations are responsible for passing their +// native identity through one of these provider-neutral boundaries. +func resolveSessionID(explicit string, explicitSet bool) (string, error) { + if explicitSet { + if explicit == "" { + return "", errEmptySessionID + } + return explicit, nil + } + return os.Getenv("ARC_SESSION_ID"), nil +} + +// resolvePrimeSessionID gives a validated Claude hook identity precedence over +// ARC_SESSION_ID unless prime was given an explicit session ID. +func resolvePrimeSessionID(explicit string, explicitSet bool, hookID string) (string, error) { + if explicitSet { + return resolveSessionID(explicit, true) } - if id := os.Getenv("ARC_SESSION_ID"); id != "" { - return id + if hookID != "" { + return hookID, nil } - return os.Getenv("CODEX_THREAD_ID") + return resolveSessionID("", false) } diff --git a/cmd/arc/session_test.go b/cmd/arc/session_test.go index 561e2e1f..2276cda0 100644 --- a/cmd/arc/session_test.go +++ b/cmd/arc/session_test.go @@ -22,6 +22,7 @@ func setupSessionTest(t *testing.T) (*client.Client, string) { t.Chdir(workDir) t.Setenv("ARC_SESSION_ID", "") t.Setenv("CODEX_THREAD_ID", "") + t.Setenv("PI_SESSION_ID", "") t.Setenv("CLAUDE_ENV_FILE", "") t.Setenv("ARC_TEAMMATE_ROLE", "") @@ -69,19 +70,32 @@ func takeTestCommand() *cobra.Command { func TestUpdateTakeSessionIdentity(t *testing.T) { tests := []struct { - name, explicit, arcID, codexID, status, wantID, wantErr string - withoutTake bool + name, explicit, arcID, codexID, piID, status, wantID, wantErr string + explicitSet, withoutTake bool }{ - {name: "explicit", explicit: "explicit-session", wantID: "explicit-session"}, + {name: "explicit", explicit: "explicit-session", explicitSet: true, wantID: "explicit-session"}, {name: "arc environment", arcID: "arc-session", wantID: "arc-session"}, - {name: "codex", codexID: "codex-thread", wantID: "codex-thread"}, - {name: "missing", wantErr: "no session ID available"}, - {name: "flag wins conflicts", explicit: "flag", arcID: "arc-session", codexID: "codex", wantID: "flag"}, - {name: "arc wins conflict", arcID: "arc-session", codexID: "codex", wantID: "arc-session"}, - {name: "matching env", arcID: "same", codexID: "same", wantID: "same"}, - {name: "preserve status", codexID: "codex", status: string(types.StatusBlocked), wantID: "codex"}, + {name: "native Codex environment is ignored", codexID: "codex-thread", wantErr: "no session ID available"}, + {name: "native Pi environment is ignored", piID: "pi-session", wantErr: "no session ID available"}, { - name: "flag requires take", explicit: "flag", codexID: "codex", withoutTake: true, + name: "missing generic identity with native environments", codexID: "codex", piID: "pi", + wantErr: "no session ID available", + }, + { + name: "flag wins conflicts", explicit: "flag", explicitSet: true, arcID: "arc-session", + codexID: "codex", piID: "pi", wantID: "flag", + }, + {name: "arc wins native conflict", arcID: "arc-session", codexID: "codex", piID: "pi", wantID: "arc-session"}, + { + name: "preserve status", explicit: "explicit", explicitSet: true, + status: string(types.StatusBlocked), wantID: "explicit", + }, + { + name: "empty explicit value does not fall back", explicitSet: true, arcID: "arc-session", + codexID: "codex", piID: "pi", wantErr: "--session-id cannot be empty", + }, + { + name: "flag requires take", explicit: "flag", explicitSet: true, codexID: "codex", withoutTake: true, wantErr: "--session-id requires --take", }, } @@ -90,13 +104,16 @@ func TestUpdateTakeSessionIdentity(t *testing.T) { c, projID := setupSessionTest(t) t.Setenv("ARC_SESSION_ID", tt.arcID) t.Setenv("CODEX_THREAD_ID", tt.codexID) + t.Setenv("PI_SESSION_ID", tt.piID) issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: "Claim fixture"}) require.NoError(t, err) cmd := takeTestCommand() if tt.withoutTake { require.NoError(t, cmd.Flags().Set("take", "false")) } - require.NoError(t, cmd.Flags().Set("session-id", tt.explicit)) + if tt.explicitSet { + require.NoError(t, cmd.Flags().Set("session-id", tt.explicit)) + } if tt.status != "" { require.NoError(t, cmd.Flags().Set("status", tt.status)) } @@ -121,25 +138,40 @@ func TestUpdateTakeSessionIdentity(t *testing.T) { } } -func TestCodexSessionRegistrationAndTake(t *testing.T) { - c, projID := setupSessionTest(t) - const threadID = "983a7cf7-bcb6-48fc-b485-129b4f1aaa45" - t.Setenv("CODEX_THREAD_ID", threadID) - cwd, err := os.Getwd() - require.NoError(t, err) - payload, err := json.Marshal(hookInput{SessionID: threadID, CWD: cwd}) - require.NoError(t, err) - sessionTestStdin(t, string(payload)) - require.NoError(t, runSessionStart(aiSessionStartCmd, true)) - registered, err := c.GetAISession(projID, threadID) - require.NoError(t, err) - issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: "Codex claim fixture"}) - require.NoError(t, err) - require.NoError(t, updateCmd.RunE(takeTestCommand(), []string{issue.ID})) - claimed, err := c.GetIssueByID(issue.ID) - require.NoError(t, err) - require.Equal(t, registered.ID, claimed.AISessionID) - require.Equal(t, types.StatusInProgress, claimed.Status) +func TestHarnessRegistrationAndExplicitTake(t *testing.T) { + tests := []struct { + name, id string + }{ + {name: "Claude", id: "983a7cf7-bcb6-48fc-b485-129b4f1aaa45"}, + {name: "Codex", id: "72b52c9a-2f32-4ae8-b387-ecde0e36e70f"}, + {name: "Pi", id: "455df4ac-2b0f-4d28-93b7-f811a8fb4b03"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c, projID := setupSessionTest(t) + cwd, err := os.Getwd() + require.NoError(t, err) + registerCmd := &cobra.Command{} + registerCmd.Flags().String("id", "", "") + registerCmd.Flags().String("transcript-path", "", "") + registerCmd.Flags().String("cwd", "", "") + require.NoError(t, registerCmd.Flags().Set("id", tt.id)) + require.NoError(t, registerCmd.Flags().Set("cwd", cwd)) + require.NoError(t, runSessionStart(registerCmd, false)) + registered, err := c.GetAISession(projID, tt.id) + require.NoError(t, err) + issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: tt.name + " claim fixture"}) + require.NoError(t, err) + claimCmd := takeTestCommand() + require.NoError(t, claimCmd.Flags().Set("session-id", tt.id)) + require.NoError(t, updateCmd.RunE(claimCmd, []string{issue.ID})) + claimed, err := c.GetIssueByID(issue.ID) + require.NoError(t, err) + require.Equal(t, registered.ID, claimed.AISessionID) + require.Equal(t, tt.id, claimed.AISessionID) + require.Equal(t, types.StatusInProgress, claimed.Status) + }) + } } func TestSessionStartKeepsExplicitIdentity(t *testing.T) { @@ -172,12 +204,35 @@ func TestSessionStartKeepsExplicitIdentity(t *testing.T) { require.Equal(t, "hook-session", sessions[0].ID) } +func primeTestCommand() *cobra.Command { + cmd := &cobra.Command{} + cmd.Flags().String("session-id", "", "") + return cmd +} + func TestPrimeSessionIdentity(t *testing.T) { const hookID = "983a7cf7-bcb6-48fc-b485-129b4f1aaa45" - tests := []struct{ name, hook, arcID, codexID, wantID string }{ - {name: "codex", codexID: "codex-thread", wantID: "codex-thread"}, - {name: "arc wins conflict", arcID: "arc-session", codexID: "codex-thread", wantID: "arc-session"}, - {name: "hook wins conflicts", hook: hookID, arcID: "arc-session", codexID: "codex-thread", wantID: hookID}, + tests := []struct { + name, explicit, hook, arcID, codexID, piID, wantID, wantErr string + explicitSet bool + }{ + { + name: "explicit wins conflicts", explicit: "explicit", explicitSet: true, hook: hookID, + arcID: "arc-session", codexID: "codex-thread", piID: "pi", wantID: "explicit", + }, + { + name: "hook wins ARC fallback", hook: hookID, arcID: "arc-session", + codexID: "codex-thread", piID: "pi", wantID: hookID, + }, + { + name: "ARC fallback ignores native environments", arcID: "arc-session", + codexID: "codex-thread", piID: "pi", wantID: "arc-session", + }, + {name: "native environments are ignored", codexID: "codex-thread", piID: "pi"}, + { + name: "empty explicit fails", explicitSet: true, hook: hookID, arcID: "arc-session", + wantErr: "--session-id cannot be empty", + }, {name: "missing"}, } for _, tt := range tests { @@ -185,12 +240,25 @@ func TestPrimeSessionIdentity(t *testing.T) { setupSessionTest(t) t.Setenv("ARC_SESSION_ID", tt.arcID) t.Setenv("CODEX_THREAD_ID", tt.codexID) + t.Setenv("PI_SESSION_ID", tt.piID) envFile := filepath.Join(t.TempDir(), "claude-env") t.Setenv("CLAUDE_ENV_FILE", envFile) payload, err := json.Marshal(hookInput{SessionID: tt.hook}) require.NoError(t, err) sessionTestStdin(t, string(payload)) - out := captureStdout(t, func() { primeCmd.Run(primeCmd, nil) }) + cmd := primeTestCommand() + if tt.explicitSet { + require.NoError(t, cmd.Flags().Set("session-id", tt.explicit)) + } + var runErr error + out := captureStdout(t, func() { runErr = primeCmd.RunE(cmd, nil) }) + if tt.wantErr != "" { + require.ErrorContains(t, runErr, tt.wantErr) + require.Empty(t, out) + require.NoFileExists(t, envFile) + return + } + require.NoError(t, runErr) if tt.wantID == "" { require.NotContains(t, out, "> **Session**:") } else { diff --git a/internal/docs/WORKFLOWS.md b/internal/docs/WORKFLOWS.md index 1cc845c7..37cdc2c9 100644 --- a/internal/docs/WORKFLOWS.md +++ b/internal/docs/WORKFLOWS.md @@ -47,16 +47,38 @@ nonempty value in this order: 1. `--session-id` (requires `--take`) 2. `ARC_SESSION_ID` -3. `CODEX_THREAD_ID`, provided by Codex for commands in the current thread -Explicit flags and `ARC_SESSION_ID` take precedence when identities conflict. -Without any identity, the command fails without updating the issue. +The CLI treats these IDs as opaque and does not read harness-specific identity +variables. Harnesses should pass their current identity explicitly, for example: + +```bash +# Claude hook identity retained as ARC_SESSION_ID +arc update --take --session-id "${ARC_SESSION_ID:?ARC_SESSION_ID is required}" +arc prime --session-id "${ARC_SESSION_ID:?ARC_SESSION_ID is required}" + +# Codex and Pi integrations pass their current native identity explicitly +arc update --take --session-id "${CODEX_THREAD_ID:?CODEX_THREAD_ID is required}" +arc update --take --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}" +``` + +Claude hooks provide their canonical UUID and can retain it through +`ARC_SESSION_ID`. Codex integrations pass the current `CODEX_THREAD_ID`, and Pi +integrations pass the current `PI_SESSION_ID` (or the extension's session-manager +identity). The missing-value guards above prevent passing an empty ID. Do not copy +a parent ID into a spawned worker; each integration passes that worker's current +identity. + +An explicitly empty `--session-id` is an error; it does not fall back to +`ARC_SESSION_ID`. Without either value, `--take` fails before updating the +issue. `--session-id` is accepted by `update` only with `--take`. + +For `arc prime`, an explicit `--session-id` wins; otherwise a valid Claude hook +payload wins over `ARC_SESSION_ID`. The hook payload must be a UUID-format session ID and +is the only input persisted to `CLAUDE_ENV_FILE`; explicit and environment +identities are never persisted. The Arc plugin's `SessionStart` hook registers the runtime's `session_id` -unchanged. In a Codex session this matches `CODEX_THREAD_ID`; no environment-file -repair is needed. `arc prime` uses the same environment fallback, while a valid -hook payload takes precedence and retains Claude's `CLAUDE_ENV_FILE` persistence. -Neither `prime` nor `--take` registers a session. Registration remains +unchanged. Neither `prime` nor `--take` registers a session. Registration remains `arc ai session start --stdin` for hooks or `arc ai session start --id --cwd ` for manual use.