diff --git a/cmd/arc/main.go b/cmd/arc/main.go index c38d1686..4cb2cddd 100644 --- a/cmd/arc/main.go +++ b/cmd/arc/main.go @@ -1052,18 +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 { - // Resolve session ID: explicit flag > env var > error - if sessionID == "" { - sessionID = os.Getenv("ARC_SESSION_ID") + sessionID, err = resolveSessionID(sessionID, sessionIDSet) + if err != nil { + return err } 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 pass --session-id") } updates["ai_session_id"] = sessionID // Set status to in_progress unless user explicitly passed --status @@ -1131,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 for the current AI session (sets ai_session_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 36971097..f10e7107 100644 --- a/cmd/arc/prime.go +++ b/cmd/arc/prime.go @@ -46,22 +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) } - // Also check env var (may have been set by a previous SessionStart hook) - if sessionID == "" { - sessionID = os.Getenv("ARC_SESSION_ID") + 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) @@ -77,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 } } @@ -85,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 @@ -97,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 @@ -115,8 +121,9 @@ Workflow customization: // Output workflow context if err := outputPrimeContext(os.Stdout, mcpMode, sessionID); err != nil { - os.Exit(0) + return nil } + return nil }, } @@ -225,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) } @@ -339,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 @@ -369,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 @@ -404,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 new file mode 100644 index 00000000..b72e3b7e --- /dev/null +++ b/cmd/arc/session.go @@ -0,0 +1,33 @@ +package main + +import ( + "errors" + "os" +) + +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 hookID != "" { + return hookID, nil + } + return resolveSessionID("", false) +} diff --git a/cmd/arc/session_test.go b/cmd/arc/session_test.go new file mode 100644 index 00000000..2276cda0 --- /dev/null +++ b/cmd/arc/session_test.go @@ -0,0 +1,276 @@ +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("PI_SESSION_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, piID, status, wantID, wantErr string + explicitSet, withoutTake bool + }{ + {name: "explicit", explicit: "explicit-session", explicitSet: true, wantID: "explicit-session"}, + {name: "arc environment", arcID: "arc-session", wantID: "arc-session"}, + {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: "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", + }, + } + 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) + 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")) + } + 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)) + } + 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 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) { + 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 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, 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 { + t.Run(tt.name, func(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)) + 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 { + 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..37cdc2c9 100644 --- a/internal/docs/WORKFLOWS.md +++ b/internal/docs/WORKFLOWS.md @@ -39,6 +39,49 @@ 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` + +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. 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")