From 94f25fe79dec273b2d43cce493d3fdabd00bef1a Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Sun, 6 Dec 2026 10:45:32 +0000 Subject: [PATCH 1/2] fix(trace): attribute shell changes in a mixed Copilot pre-tool batch Signed-off-by: jay23606 <4602056+jay23606@users.noreply.github.com> --- app/cli/internal/trace/copilot/hooks.go | 33 ++++++++++++----- app/cli/internal/trace/copilot/hooks_test.go | 5 +++ app/cli/pkg/action/trace_agent_hook.go | 35 ++++++++++++++---- app/cli/pkg/action/trace_agent_hook_test.go | 38 ++++++++++++++++++++ 4 files changed, 96 insertions(+), 15 deletions(-) diff --git a/app/cli/internal/trace/copilot/hooks.go b/app/cli/internal/trace/copilot/hooks.go index e47a92c3f..d01eae9f0 100644 --- a/app/cli/internal/trace/copilot/hooks.go +++ b/app/cli/internal/trace/copilot/hooks.go @@ -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. @@ -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 @@ -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 { diff --git a/app/cli/internal/trace/copilot/hooks_test.go b/app/cli/internal/trace/copilot/hooks_test.go index ead64953a..87c6b74ff 100644 --- a/app/cli/internal/trace/copilot/hooks_test.go +++ b/app/cli/internal/trace/copilot/hooks_test.go @@ -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"}`, diff --git a/app/cli/pkg/action/trace_agent_hook.go b/app/cli/pkg/action/trace_agent_hook.go index 6e139d682..50a05f820 100644 --- a/app/cli/pkg/action/trace_agent_hook.go +++ b/app/cli/pkg/action/trace_agent_hook.go @@ -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 @@ -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 := locateForHook(provider, input) + 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") @@ -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") diff --git a/app/cli/pkg/action/trace_agent_hook_test.go b/app/cli/pkg/action/trace_agent_hook_test.go index 6e883c099..c31f47cee 100644 --- a/app/cli/pkg/action/trace_agent_hook_test.go +++ b/app/cli/pkg/action/trace_agent_hook_test.go @@ -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" @@ -833,6 +834,43 @@ 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) +} + // 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). From 6fd9cc8922843421f889ec15ba4e7362d760705d Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Sun, 6 Dec 2026 07:00:04 -0500 Subject: [PATCH 2/2] fix(trace): locate mixed batch shell snapshot from cwd Signed-off-by: jay23606 <4602056+jay23606@users.noreply.github.com> --- app/cli/pkg/action/trace_agent_hook.go | 2 +- app/cli/pkg/action/trace_agent_hook_test.go | 30 +++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/app/cli/pkg/action/trace_agent_hook.go b/app/cli/pkg/action/trace_agent_hook.go index 50a05f820..c56eac76c 100644 --- a/app/cli/pkg/action/trace_agent_hook.go +++ b/app/cli/pkg/action/trace_agent_hook.go @@ -407,7 +407,7 @@ func HandleAgentPreToolUse(provider trace.Provider, log zerolog.Logger) error { // 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 := locateForHook(provider, input) + store, repoRoot, err := state.Locate() if err != nil { log.Debug().Err(err).Msg("pre-tool-use: no trace state located for batch command") return diff --git a/app/cli/pkg/action/trace_agent_hook_test.go b/app/cli/pkg/action/trace_agent_hook_test.go index c31f47cee..481b24aa9 100644 --- a/app/cli/pkg/action/trace_agent_hook_test.go +++ b/app/cli/pkg/action/trace_agent_hook_test.go @@ -871,6 +871,36 @@ func TestHandleAgentCopilotBatchShellAttribution(t *testing.T) { 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).