Skip to content
Draft
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
33 changes: 24 additions & 9 deletions app/cli/internal/trace/copilot/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,13 @@ type hookPayload struct {
ToolInput json.RawMessage `json:"tool_input"`
// ToolCalls is the pre-tool form of older Copilot CLI releases: one
// hook for a batch of calls.
ToolCalls []struct {
Name string `json:"name"`
Args json.RawMessage `json:"args"`
} `json:"toolCalls"`
ToolCalls []toolCall `json:"toolCalls"`
}

// toolCall is one call of a batched pre-tool hook.
type toolCall struct {
Name string `json:"name"`
Args json.RawMessage `json:"args"`
}

// toolArgs are the arguments of the file and shell tools that Trace reads.
Expand Down Expand Up @@ -377,7 +380,9 @@ func patchPaths(patch, cwd string) []string {
}

// readToolCalls maps a batch of calls to one input. File tools win over a
// shell tool, because their per-file snapshots are exact. Each later
// shell tool as ToolName, because their per-file snapshots are exact. When
// the batch also runs a shell command, its Command is kept too, so the
// handler snapshots the worktree for the command as well. Each later
// post-tool hook carries one call.
func (p *Provider) readToolCalls(input *trace.HookInput, raw hookPayload) {
var paths []string
Expand All @@ -396,16 +401,26 @@ func (p *Provider) readToolCalls(input *trace.HookInput, raw hookPayload) {
}
if input.ToolName != "" {
setPaths(input, paths)
if call, ok := firstCommandCall(p, raw.ToolCalls); ok {
input.Command = decodeToolArgs(call.Args).Command
}
return
}

for _, call := range raw.ToolCalls {
if call, ok := firstCommandCall(p, raw.ToolCalls); ok {
input.ToolName = call.Name
input.Command = decodeToolArgs(call.Args).Command
}
}

// firstCommandCall returns the first call of a batch that runs a shell command.
func firstCommandCall(p *Provider, calls []toolCall) (toolCall, bool) {
for _, call := range calls {
if p.IsCommandTool(call.Name) {
input.ToolName = call.Name
input.Command = decodeToolArgs(call.Args).Command
return
return call, true
}
}
return toolCall{}, false
}

func absPath(path, cwd string) string {
Expand Down
5 changes: 5 additions & 0 deletions app/cli/internal/trace/copilot/hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@ func TestReadHookInput(t *testing.T) {
payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCalls":[{"id":"t1","name":"report_intent","args":"{}"},{"id":"t2","name":"bash","args":"{\"command\":\"go test\"}"}]}`,
want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolBash, Command: "go test"},
},
{
name: "pre tool, batched file and shell calls keep both",
payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCalls":[{"id":"t1","name":"create","args":"{\"path\":\"/work/repo/a.md\",\"file_text\":\"x\"}"},{"id":"t2","name":"bash","args":"{\"command\":\"go test\"}"}]}`,
want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolCreate, FilePath: "/work/repo/a.md", Command: "go test"},
},
{
name: "post tool, apply_patch with the patch as a string",
payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCallId":"c1","toolName":"apply_patch","toolArgs":"*** Begin Patch\n*** Add File: /work/repo/greeting.txt\n+hello\n*** End Patch\n"}`,
Expand Down
35 changes: 29 additions & 6 deletions app/cli/pkg/action/trace_agent_hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,13 @@ func HandleAgentPreToolUse(provider trace.Provider, log zerolog.Logger) error {
return nil
}

// A batch can hold a file tool and a shell command. The shell command
// gets one worktree snapshot for the batch, and the files are
// snapshotted one by one below.
if input.Command != "" && provider.IsFileWritingTool(input.ToolName) {
handleBatchShellPreToolUse(provider, input, log)
}

for _, fileInput := range fileHookInputs(input) {
if err := handleAgentPreToolUse(provider, fileInput, log); err != nil {
return err
Expand All @@ -397,6 +404,27 @@ func HandleAgentPreToolUse(provider trace.Provider, log zerolog.Logger) error {
return nil
}

// handleBatchShellPreToolUse snapshots the worktree for the shell command of
// a batch that also runs a file tool.
func handleBatchShellPreToolUse(provider trace.Provider, input *trace.HookInput, log zerolog.Logger) {
store, repoRoot, err := state.Locate()
if err != nil {
log.Debug().Err(err).Msg("pre-tool-use: no trace state located for batch command")
return
}
ensureSessionTracked(provider, store, repoRoot, input, log)
snapshotShellCommand(provider, store, repoRoot, input, log)
}

// snapshotShellCommand snapshots the whole worktree so the post hook can diff
// it and attribute the command's file changes to the AI. It registers the
// checkouts the command names first, so the snapshot covers them.
func snapshotShellCommand(provider trace.Provider, store *state.Store, repoRoot string, input *trace.HookInput, log zerolog.Logger) {
registerCommandCheckouts(provider, input, repoRoot, log)
captureWorktreeSnapshot(store, repoRoot, shellCallKey(input), log)
tagShellCommand(provider, input, log)
}

func handleAgentPreToolUse(provider trace.Provider, input *trace.HookInput, log zerolog.Logger) error {
log.Debug().Str("session_id", input.SessionID).Msg("pre-tool-use hook invoked")

Expand All @@ -411,12 +439,7 @@ func handleAgentPreToolUse(provider trace.Provider, input *trace.HookInput, log

switch {
case provider.IsCommandTool(input.ToolName):
// Shell command: snapshot the whole worktree so the post hook can diff
// it and attribute the command's file changes to the AI. Register the
// checkouts the command names first, so the snapshot covers them.
registerCommandCheckouts(provider, input, repoRoot, log)
captureWorktreeSnapshot(store, repoRoot, shellCallKey(input), log)
tagShellCommand(provider, input, log)
snapshotShellCommand(provider, store, repoRoot, input, log)
case provider.IsFileWritingTool(input.ToolName):
if input.FilePath == "" {
log.Debug().Str("tool", input.ToolName).Msg("pre-tool-use: file-writing tool produced no file path, skipping")
Expand Down
68 changes: 68 additions & 0 deletions app/cli/pkg/action/trace_agent_hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (

"github.com/chainloop-dev/chainloop/app/cli/internal/trace"
"github.com/chainloop-dev/chainloop/app/cli/internal/trace/claude"
"github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot"
"github.com/chainloop-dev/chainloop/app/cli/internal/trace/cursor"
"github.com/chainloop-dev/chainloop/app/cli/internal/trace/hooks"
"github.com/chainloop-dev/chainloop/app/cli/internal/trace/opencode"
Expand Down Expand Up @@ -833,6 +834,73 @@ func TestHandleAgentCursorShellCommand(t *testing.T) {
assert.Error(t, err, "pre-command signature is cleaned up")
}

// TestHandleAgentCopilotBatchShellAttribution drives the pre-tool hook with a
// Copilot batch that holds a file tool and a shell command. The shell command's
// worktree changes must still be attributed to the AI by the post hook.
func TestHandleAgentCopilotBatchShellAttribution(t *testing.T) {
dir, gitDir := initGitRepo(t)
store := state.NewGitStore(gitDir)
require.NoError(t, store.InitTraceDir())

p := copilot.New()
const session = "ses-batch"

preArgs, err := json.Marshal(map[string]string{"path": filepath.Join(dir, "a.md"), "file_text": "x"})
require.NoError(t, err)
preBatch, err := json.Marshal(map[string]any{
"sessionId": session,
"cwd": dir,
"toolCalls": []map[string]any{
{"id": "t1", "name": "create", "args": string(preArgs)},
{"id": "t2", "name": "bash", "args": `{"command":"go test"}`},
},
})
require.NoError(t, err)
withStdin(t, string(preBatch))
require.NoError(t, HandleAgentPreToolUse(p, zerolog.Nop()))

// The shell command creates a file; the file tool wrote a.md.
require.NoError(t, os.WriteFile(filepath.Join(dir, "generated.txt"), []byte("1\n2\n3\n"), 0600))
require.NoError(t, os.WriteFile(filepath.Join(dir, "a.md"), []byte("x"), 0600))

withStdin(t, `{"sessionId":"ses-batch","cwd":"`+filepath.ToSlash(dir)+`","toolName":"bash","toolArgs":{"command":"go test"}}`)
require.NoError(t, HandleAgentPostToolUse(p, zerolog.Nop()))

attr := store.LoadAILineAttribution(session)
require.Contains(t, attr.Files, "generated.txt", "shell change of a mixed batch is attributed")
assert.Equal(t, 3, attr.Files["generated.txt"][0].End)
}

func TestHandleAgentCopilotBatchShellUsesSessionCheckout(t *testing.T) {
home := chdirToResolvedGitRepo(t)
other := resolvedTempGitRepo(t)
homeStore := state.NewGitStore(filepath.Join(home, ".git"))
otherStore := state.NewGitStore(filepath.Join(other, ".git"))
require.NoError(t, homeStore.InitTraceDir())
require.NoError(t, otherStore.InitTraceDir())

p := copilot.New()
const session = "ses-batch-other-checkout"
fileArgs, err := json.Marshal(map[string]string{"path": filepath.Join(other, "a.md"), "file_text": "x"})
require.NoError(t, err)
preBatch, err := json.Marshal(map[string]any{
"sessionId": session,
"cwd": home,
"toolCalls": []map[string]any{
{"id": "t1", "name": "create", "args": string(fileArgs)},
{"id": "t2", "name": "bash", "args": `{"command":"go test"}`},
},
})
require.NoError(t, err)
withStdin(t, string(preBatch))
require.NoError(t, HandleAgentPreToolUse(p, zerolog.Nop()))

_, err = homeStore.LoadShellPreSignature(state.ShellCallKey{SessionID: session})
require.NoError(t, err, "the shell snapshot belongs to the session checkout")
_, err = otherStore.LoadShellPreSignature(state.ShellCallKey{SessionID: session})
assert.Error(t, err, "the file tool checkout must not own the shell snapshot")
}

// TestHandleAgentClaudeCodeSession drives the pre/post-tool-use handlers with
// the real JSON payloads Claude Code pipes to its hooks, across a full session:
// SessionStart → Write (new file) → Edit (modify it) → Bash (generate a file).
Expand Down