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
18 changes: 18 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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"

Expand Down
2 changes: 1 addition & 1 deletion cmd/arc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1059,7 +1059,7 @@ var updateCmd = &cobra.Command{
}

if take {
sessionID, err = resolveSessionID(sessionID, sessionIDSet)
sessionID, err = resolveClaimSessionID(c, args[0], sessionID, sessionIDSet)
if err != nil {
return err
}
Expand Down
6 changes: 4 additions & 2 deletions cmd/arc/prime.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,8 @@ You are the **{{.Role}}** teammate.

var tmplCLI = template.Must(template.New("cli").Parse(`# Arc Workflow Context

> **Context Recovery**: Run ` + "`arc prime`" + ` after compaction, clear, or new session
> **Context Recovery**: Run ` + "`arc prime --session-id <session-id>`" + ` after compaction,
> clear, or a new manual session
> Hooks auto-call this in Claude Code when project config detected
{{- if .SessionID}}
> **Session**: ` + "`{{.SessionID}}`" + `
Expand Down Expand Up @@ -355,7 +356,8 @@ var tmplCLI = template.Must(template.New("cli").Parse(`# Arc Workflow Context
` + "`arc prime --session-id <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.
- ` + "`prime`" + ` does not register sessions. ` + "`--take`" + ` registers or reuses the selected session in
the issue's project before changing issue ownership or status.

## Essential Commands

Expand Down
3 changes: 2 additions & 1 deletion cmd/arc/prime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ func TestPrime(t *testing.T) {
{"documents --parallel flag", "--parallel"},
{"documents generic session identity", "ARC_SESSION_ID"},
{"documents explicit session identity", "--session-id"},
{"documents separate registration", "do not register sessions"},
{"documents prime non-registration", "prime` does not register sessions"},
{"documents claim registration", "--take` registers or reuses"},
}

for _, tt := range tests {
Expand Down
43 changes: 43 additions & 0 deletions cmd/arc/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ package main

import (
"errors"
"fmt"
"os"

"github.com/sentiolabs/arc/internal/client"
"github.com/sentiolabs/arc/internal/types"
)

var errEmptySessionID = errors.New("--session-id cannot be empty")
Expand All @@ -20,6 +24,36 @@ func resolveSessionID(explicit string, explicitSet bool) (string, error) {
return os.Getenv("ARC_SESSION_ID"), 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, explicitSet bool) (string, error) {
id, err := resolveSessionID(explicit, explicitSet)
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)
}

// 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) {
Expand All @@ -31,3 +65,12 @@ func resolvePrimeSessionID(explicit string, explicitSet bool, hookID string) (st
}
return resolveSessionID("", false)
}

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 id, nil
}
128 changes: 119 additions & 9 deletions cmd/arc/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -134,6 +137,14 @@ 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)
}
})
}
}
Expand All @@ -151,17 +162,14 @@ func TestHarnessRegistrationAndExplicitTake(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)
registered, err := c.CreateAISession(projID, &types.AISession{
ID: tt.id, CWD: cwd, TranscriptPath: "/recorded/transcript.jsonl",
})
require.NoError(t, err)
issue, err := c.CreateIssue(projID, client.CreateIssueRequest{Title: tt.name + " claim fixture"})
require.NoError(t, err)
// A registered parent remains usable from a worker's different directory.
t.Chdir(t.TempDir())
claimCmd := takeTestCommand()
require.NoError(t, claimCmd.Flags().Set("session-id", tt.id))
require.NoError(t, updateCmd.RunE(claimCmd, []string{issue.ID}))
Expand All @@ -170,10 +178,109 @@ func TestHarnessRegistrationAndExplicitTake(t *testing.T) {
require.Equal(t, registered.ID, claimed.AISessionID)
require.Equal(t, tt.id, claimed.AISessionID)
require.Equal(t, types.StatusInProgress, claimed.Status)
require.NoError(t, updateCmd.RunE(claimCmd, []string{issue.ID}))
retried, err := c.GetAISession(projID, tt.id)
require.NoError(t, err)
require.Equal(t, *registered, 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)
claimCmd := takeTestCommand()
require.NoError(t, claimCmd.Flags().Set("session-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(claimCmd, []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) {
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 })
claimCmd := takeTestCommand()
require.NoError(t, claimCmd.Flags().Set("session-id", "worker-thread"))
err := updateCmd.RunE(claimCmd, []string{"fixture"})
require.ErrorContains(t, err, "register AI session")
require.False(t, updated.Load(), "registration failure must stop before issue mutation")
})
}
}

func TestEmptyClaimIDSkipsAPICalls(t *testing.T) {
var calls atomic.Int32
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.WriteHeader(http.StatusInternalServerError)
}))
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 })

claimCmd := takeTestCommand()
require.NoError(t, claimCmd.Flags().Set("session-id", ""))
err := updateCmd.RunE(claimCmd, []string{"fixture"})
require.ErrorIs(t, err, errEmptySessionID)
require.Zero(t, calls.Load(), "an empty explicit session ID must fail before API requests")
}

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) {
c, projID := setupSessionTest(t)
t.Setenv("ARC_SESSION_ID", "arc-env")
Expand Down Expand Up @@ -237,7 +344,7 @@ func TestPrimeSessionIdentity(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setupSessionTest(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)
Expand Down Expand Up @@ -271,6 +378,9 @@ func TestPrimeSessionIdentity(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "export ARC_SESSION_ID="+tt.hook+"\n", string(data))
}
sessions, err := c.ListAISessions(projID, 10, 0)
require.NoError(t, err)
require.Empty(t, sessions, "prime must not lazily register sessions")
})
}
}
3 changes: 3 additions & 0 deletions internal/api/ai_sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
24 changes: 24 additions & 0 deletions internal/api/ai_sessions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Loading