diff --git a/app/cli/internal/trace/README.md b/app/cli/internal/trace/README.md index 60bca744b..cad189fce 100644 --- a/app/cli/internal/trace/README.md +++ b/app/cli/internal/trace/README.md @@ -28,11 +28,11 @@ In a linked Git worktree, Codex 0.163 reads project hooks from the primary check Codex evidence converts native messages, tool calls, and tool results to the message shape used by the existing session viewer. Text uses `message.content`, calls use `tool_use` blocks, and results use `tool_result` blocks with matching IDs. Each converted entry retains its event in `source_event`. Spec and pasted-image pointers replace copies in viewer messages, retained events, and supported native timeline records. Other native metadata stays unchanged. Codex regression and E2E checks require renderable messages. When tools are used, they also require a completed exchange with readable tool output. A nonempty native transcript alone does not pass. These checks apply to Codex; `raw_session` remains open in the shared evidence schema. -GitHub Copilot uses one provider for Copilot CLI and the Copilot agent in VS Code (spec issue-3800). Both read the hook files in `.github/hooks/`, and Trace owns its own file there, `.github/hooks/chainloop-trace.json`. Run `chainloop trace init --copilot` or `chainloop trace run --local --copilot -- copilot …`. Copilot CLI loads the repository hooks only in a trusted folder: trust the repository when Copilot asks, or pass `--trust-folder` to a prompt-mode run. In a folder that is not trusted, Copilot skips the hooks and Trace records nothing. Trace does not support the older VS Code agent that GitHub calls the "Local" harness. Trace reads the session event log from `$COPILOT_HOME/session-state//events.jsonl` (default `~/.copilot`). Its format is not a stable Copilot interface. Token usage comes from the `session.shutdown` summary, which Copilot writes after the last hook, so the push reads it from a fresh copy. Without a summary, usage comes from the records of each call, or from the output tokens of each message, with a warning. Cost is an estimate from the embedded API prices, not the Copilot bill (subscription and premium requests). The Copilot hooks carry no tool call ID, so two tool calls on the same file at the same time share one snapshot (TRC-006). +GitHub Copilot uses one provider for Copilot CLI and the Copilot agent in VS Code (spec issue-3800). Both read the hook files in `.github/hooks/`, and Trace owns its own file there, `.github/hooks/chainloop-trace.json`. Run `chainloop trace init --copilot` or `chainloop trace run --local --copilot -- copilot …`. Copilot CLI loads the repository hooks only in a trusted folder: trust the repository when Copilot asks, or pass `--trust-folder` to a prompt-mode run. In a folder that is not trusted, Copilot skips the hooks and Trace records nothing. Trace does not support the older VS Code agent that GitHub calls the "Local" harness. Trace reads the session event log from `$COPILOT_HOME/session-state//events.jsonl` (default `~/.copilot`). Its format is not a stable Copilot interface. The log keeps each image in a `session.binary_asset` record, which a message refers to by its digest. Trace stores an image that the user attached to a message, and replaces the data of its record with a pointer. An image that a tool gives the model, such as a `view` of an image file, stays inline. Token usage comes from the `session.shutdown` summary, which Copilot writes after the last hook, so the push reads it from a fresh copy. Without a summary, usage comes from the records of each call, or from the output tokens of each message, with a warning. Cost is an estimate from the embedded API prices, not the Copilot bill (subscription and premium requests). The Copilot hooks carry no tool call ID, so two tool calls on the same file at the same time share one snapshot (TRC-006). The Copilot agent also runs the hooks in `.claude/settings.json`. The Claude Code provider ignores Copilot payloads, so a repository with both providers records a Copilot session once, under Copilot. -Copilot CLI 1.0.109 with `gpt-6.1-sol` on an Azure OpenAI provider passed all 26 checked features of the end-to-end suite, and the model-driven spec checks passed 3/3. The Copilot agent in VS Code has no headless mode, so the suite does not run it, and the column shows the results of Copilot CLI. With a GPT model, Copilot edits files with `apply_patch`, which the provider records file by file, as for Codex. The welcome message was checked by hand: Copilot shows the progress line of the `sessionStart` hook in its timeline, and the suite cannot read it, because the headless output does not tell which hook wrote a line. The cells marked **No** are features that the provider does not implement. +Copilot CLI 1.0.109 with `gpt-6.1-sol` on an Azure OpenAI provider passed all 27 checked features of the end-to-end suite, skills tracking, spec source pointers, pasted image pointers, and cache token accounting included. The model-driven checks passed 3/3. The suite attaches the pasted image with `--attachment`. The Copilot agent in VS Code has no headless mode, so the suite does not run it, and the column shows the results of Copilot CLI. With a GPT model, Copilot edits files with `apply_patch`, which the provider records file by file, as for Codex. The welcome message was checked by hand: Copilot shows the progress line of the `sessionStart` hook in its timeline, and the suite cannot read it, because the headless output does not tell which hook wrote a line. The cells marked **No** are features that the provider does not implement. ## Setup @@ -57,7 +57,7 @@ What the session evidence holds about the conversation. |---------|---------------|-------------|--------|--------------|------------|---|---|---| | Transcript | The evidence holds the conversation (`raw_session`): the messages and the tool calls of the agent. | Yes | Yes | Partial | Partial | Yes | Yes | Yes | | Token usage and cost | The evidence holds the tokens that the session used and their cost in USD. | Yes | No | Yes | Yes | Yes | Yes | Yes | -| Cache token accounting | Cache reads and writes stay in separate evidence fields. Base input and total exclude cache. The suite compares stored token counts with the raw usage records. | Unknown | No | Unknown | Unknown | Yes | Unknown | Unknown | +| Cache token accounting | Cache reads and writes stay in separate evidence fields. Base input and total exclude cache. The suite compares stored token counts with the raw usage records. | Unknown | No | Unknown | Unknown | Yes | Unknown | Yes | | Model detection | The evidence names the primary model and the other models that the session used. | Yes | Partial | Yes | Yes | Yes | Yes | Yes | | Subagents | The evidence holds the conversations of the subagents, and their token usage, as part of the session. | Yes | No | No | No | No | No | No | | Missed session start | A session whose session-start hook did not fire is still recorded, from its first tool hook. | Yes | Unknown | Unknown | Yes | Yes | Unknown | Unknown | @@ -75,7 +75,6 @@ Why not Yes: - **Subagents, Codex:** the initial provider records only the root session transcript. Child-session transcripts are not collected. - **Subagents, Cursor:** the provider does not read subagent conversations. - **Subagents, Copilot:** Copilot writes no separate child transcripts. The events of a subagent are in the log of the parent, and the session totals include their tokens, but the evidence has no subagent entries (spec issue-3800). -- **Cache token accounting, Copilot:** the end-to-end check has no source comparison for the Copilot event log yet. - **Missed session start, Copilot:** the scenario needs hook messages that Copilot does not report in headless mode. - **Subagents, OpenCode:** a subagent runs in a child session with its own export. It is not part of the evidence of its parent session. - **Missed session start, Cursor and OpenCode 1.x:** not verified yet. The end-to-end suite finds the values (spec issue-3635). @@ -140,9 +139,9 @@ What the session was asked to build, and which skills it used. | Local spec sources read at push | A capture whose source is a local file holds only a header and a placeholder. Each push reads the file and records its current content, so the evidence follows the edits of the file. Only a regular text file of up to 1 MiB is read. Otherwise the push keeps the body that the agent wrote, or drops the capture with a warning when there is no body (spec issue-3561). | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Spec source role, title, and description | Each captured spec source holds the role, the title, and the description that the agent wrote in its header (spec issue-3531). | Yes | Yes | Unknown | Yes | Yes | Yes | Yes | | HTML spec sources | A captured text spec source whose body is an HTML page (it starts with a doctype or an `html` element) is stored as an `.html` file that holds only the page, without the header. The annotations and the spec entry keep the values of the header. A body that only contains HTML tags stays as the agent wrote it (issue 3707). | Yes | Yes | Unknown | Yes | Yes | Unknown | Yes | -| Skills tracking | The evidence lists the skills that the session used, with a copy of each skill as it ran. | Yes | No | Partial | Partial | Partial | Partial | No | -| Spec source pointers | Exact copies of spec sources in the transcript (full file reads and file writes) are replaced with a pointer to the spec material, so the evidence does not hold the same content two or three times (spec issue-3556). This includes the copies of pasted images and spec sources in the `api-request-blob` records of a Claude Code transcript (issue 3654). | Yes | No | No | No | No | Partial | No | -| Pasted image pointers | Each distinct image that the user pasted into the session, including images in prompts sent while the agent was busy, is stored once as an image spec entry, from the data in the transcript, with the title "Pasted image N" and no role. A repeated paste of the same image adds no entry. The inline image in the transcript is replaced with a pointer to that material. An image whose data cannot be decoded, or that the push could not store, stays inline, and the push continues. When the agent captured the same image, its entry is kept and no second entry is added (spec issue-3569). | Yes | No | No | No | No | Yes | No | +| Skills tracking | The evidence lists the skills that the session used, with a copy of each skill as it ran. | Yes | No | Partial | Partial | Partial | Partial | Partial | +| Spec source pointers | Exact copies of spec sources in the transcript (full file reads and file writes) are replaced with a pointer to the spec material, so the evidence does not hold the same content two or three times (spec issue-3556). This includes the copies of pasted images and spec sources in the `api-request-blob` records of a Claude Code transcript (issue 3654). | Yes | No | No | No | No | Partial | Partial | +| Pasted image pointers | Each distinct image that the user pasted into the session, including images in prompts sent while the agent was busy, is stored once as an image spec entry, from the data in the transcript, with the title "Pasted image N" and no role. A repeated paste of the same image adds no entry. The inline image in the transcript is replaced with a pointer to that material. An image whose data cannot be decoded, or that the push could not store, stays inline, and the push continues. When the agent captured the same image, its entry is kept and no second entry is added (spec issue-3569). | Yes | No | No | No | No | Yes | Yes | Why not Yes: @@ -156,7 +155,8 @@ Why not Yes: - **Pasted image pointers, Codex:** extracts base64 image data URLs from user input, deduplicates their decoded bytes, and replaces stored copies in both viewer messages and retained events. Tool-result images are not pastes. Invalid data, remote URLs, and path-only image records remain inline. - **Skills tracking, Pi:** completed model `read` calls are tracked only for filesystem `SKILL.md` files in the current working directory's `.pi/skills`, `.agents/skills` from there through the Git root, Pi's user skill locations, or managed package installation trees. Reads elsewhere, including unconfigured `.claude/skills`, and reads with an explicit limit or starting after line 1 are not tracked. Managed package paths are recognized by their installation trees, not by reproducing Pi's enabled-resource catalog. Native `/skill:` expansions remain tracked on the selected root branch. Skill folders are snapshotted by the first following Trace hook; push-time fallback keeps the shared warning. Child streams and arbitrary shell reads are not tracked. Pi has no managed organization-root metadata, so unclassified external locations stay `unknown`. A manual Pi 1.3.0 check with `openai-codex/gpt-6.1-sol` loaded and reloaded a project skill and retained the original definition and supporting file after the source changed. The automated suite's pinned OpenRouter run remains blocked by an expired API key. - **Spec capture reminder, Copilot:** Copilot drops the output of the `userPromptSubmitted` hook, so the provider installs no prompt hook. The agent gets the session-start instruction only. -- **Skills tracking, spec source pointers, and pasted image pointers, Copilot:** not implemented yet. They are the second milestone of spec issue-3800. +- **Skills tracking, Copilot:** a use is a `skill.invoked` event in the Copilot event log. Copilot writes it when it loads a skill into the session, so a skill listing does not count. Uses in subagents count. A skill with no `SKILL.md` path is not recorded. A skill that the user starts with a slash command counts as a user use when Copilot marks its trigger as user-started. Nobody has checked this yet: a prompt-mode run sends a slash command to the model as text, so the end-to-end suite checks only a skill that the model loads. +- **Spec source pointers, Copilot:** Trace replaces the result of a full `view` of a source file, a shell output that is exactly the source, the copy of a source that a shell command read with `cat` in a combined output (the copy must start and end at line boundaries, and the file must be unchanged at the push), the text of a `create` call, and an `apply_patch` call that adds exactly one file. The same copies in the `hook.start` records, where Copilot logs the input of each Trace hook, are replaced too. Partial views, changed content, failed tool calls, `edit` calls, and other patches stay inline. - **Skills tracking, Cursor:** the provider does not track skills. The evidence has no skill entries, which means "not recorded", not "no skill used". - **Skills tracking, OpenCode:** only the skills that the model starts with the `skill` tool are counted. Skills that the user starts, and skills used in subagents, are not. A plugin installed by an earlier version does not send the skill folder for OpenCode 2: install the hooks again to update it. - **Spec source pointers, Cursor and OpenCode:** the provider has no finder for the copies in its transcript yet. For OpenCode, the rebuilt transcript holds no tool outputs, so only the write copies would apply. @@ -231,7 +231,7 @@ The harnesses run as follows: - OpenCode runs on a private server (`opencode run --standalone`) with `PWD` set to the workspace. - Cursor runs with `cursor-agent -p --output-format stream-json --force --trust` and an isolated `HOME`. Shell startup files restore the test CLI to the front of `PATH`, including after macOS `path_helper` runs. The isolated home has no stored login, so the run needs `CURSOR_API_KEY`. The headless CLI cannot attach a pasted image or report hook messages. - Pi runs with `pi -p --mode json --approve`. -- Copilot runs with `copilot -p --trust-folder --allow-all-tools --no-ask-user` and an isolated `COPILOT_HOME`. The isolated home has no stored login, so the run needs a token with Copilot access in `COPILOT_GITHUB_TOKEN`, `GH_TOKEN` or `GITHUB_TOKEN`, or a model provider of your own in the `COPILOT_PROVIDER_*` variables. The headless CLI cannot attach a pasted image or report hook messages. The Copilot agent in VS Code has no headless mode, so a person checks it by hand. +- Copilot runs with `copilot -p --trust-folder --allow-all-tools --no-ask-user` and an isolated `COPILOT_HOME`. The isolated home has no stored login, so the run needs a token with Copilot access in `COPILOT_GITHUB_TOKEN`, `GH_TOKEN` or `GITHUB_TOKEN`, or a model provider of your own in the `COPILOT_PROVIDER_*` variables. The harness attaches a pasted image with `--attachment`. The headless CLI cannot report hook messages. The Copilot agent in VS Code has no headless mode, so a person checks it by hand. - Codex runs with `codex exec --json`, an isolated `CODEX_HOME`, no sandbox, and no hook trust prompt. The isolated configuration disables personal and bundled skills while keeping project skills available. For bundled OpenAI models on OpenRouter, the harness preserves native instructions and patch tools by aliasing the model metadata to OpenRouter's prefixed model ID. The configured OpenCode 2, Pi, and Codex models use OpenRouter and need `OPENROUTER_API_KEY`. A Codex model without the `openrouter/` prefix uses the default Codex provider and needs `CODEX_API_KEY`. The pinned Codex model is `openrouter/openai/gpt-6-luna`. GPT-5 Mini frequently ended the scripted task before committing and pushing, so it is not the default test model. diff --git a/app/cli/internal/trace/copilot/copy.go b/app/cli/internal/trace/copilot/copy.go index 9d04d13d6..36325cf07 100644 --- a/app/cli/internal/trace/copilot/copy.go +++ b/app/cli/internal/trace/copilot/copy.go @@ -31,16 +31,25 @@ import ( // eventsFile is the name of the session event log in a session folder. const eventsFile = "events.jsonl" +// copilotHomeDir returns the Copilot configuration folder: $COPILOT_HOME, or +// ~/.copilot. It returns "" when neither is known. +func copilotHomeDir() string { + if home := os.Getenv("COPILOT_HOME"); home != "" { + return home + } + userHome, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(userHome, ".copilot") +} + // sessionStateRoot returns the folder where Copilot keeps its sessions: // $COPILOT_HOME/session-state, or ~/.copilot/session-state. func sessionStateRoot() string { - home := os.Getenv("COPILOT_HOME") + home := copilotHomeDir() if home == "" { - userHome, err := os.UserHomeDir() - if err != nil { - return "" - } - home = filepath.Join(userHome, ".copilot") + return "" } return filepath.Join(home, "session-state") } diff --git a/app/cli/internal/trace/copilot/materials.go b/app/cli/internal/trace/copilot/materials.go new file mode 100644 index 000000000..82858d029 --- /dev/null +++ b/app/cli/internal/trace/copilot/materials.go @@ -0,0 +1,816 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package copilot + +import ( + "encoding/base64" + "encoding/json" + "io" + "os" + "path/filepath" + "regexp" + "slices" + "sort" + "strings" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pointer" +) + +var ( + _ trace.SpecCopyReplacer = (*Provider)(nil) + _ trace.PastedImageFinder = (*Provider)(nil) +) + +const ( + // viewTool reads a file, or a range of its lines. + viewTool = "view" + // createTool writes a new file with the text of its file_text argument. + createTool = "create" + + sourceEventField = "source_event" + dataField = "data" + resultField = "result" + // textBlock is the type of a text block of a viewer message. + textBlock = "text" +) + +// shellEnvelope matches the status line that Copilot adds after the output +// of a shell tool: "" in older releases, and +// "" in newer ones. +var shellEnvelope = regexp.MustCompile(`(?s)^(.*?)\n?(<(?:exited|shellId: [^>\n]* completed) with exit code (-?\d+)>\s*)$`) + +// jsonObject keeps the fields of an event that Trace does not change, and +// fields that a later Copilot release adds, without a decode into any. +type jsonObject map[string]json.RawMessage + +func object(raw json.RawMessage) jsonObject { + var v jsonObject + _ = json.Unmarshal(raw, &v) + return v +} + +func jsonString(raw json.RawMessage) string { + var s string + _ = json.Unmarshal(raw, &s) + return s +} + +func encodeJSON(v any) json.RawMessage { + b, _ := json.Marshal(v) // all callers give JSON values or typed structures + return b +} + +// nativeEvent returns the event of a raw session line as Copilot wrote it: +// the source_event of a viewer line, or the line itself. +func nativeEvent(line json.RawMessage) (logEvent, jsonObject, bool) { + raw := line + if source := object(line)[sourceEventField]; len(source) > 0 { + raw = source + } + var e logEvent + if json.Unmarshal(raw, &e) != nil || e.Type == "" { + return logEvent{}, nil, false + } + data := object(e.Data) + return e, data, data != nil +} + +// updateEvent writes data into the event of a raw session line. For a viewer +// line, it also builds the viewer message again from the changed event, so +// that no copy stays in either form. +func updateEvent(line json.RawMessage, data jsonObject) json.RawMessage { + fields := object(line) + if fields == nil { + return line + } + source, wrapped := fields[sourceEventField] + native := fields + if wrapped { + if native = object(source); native == nil { + return line + } + } + native[dataField] = encodeJSON(data) + updated := encodeJSON(native) + if !wrapped { + return updated + } + + var e logEvent + var d eventData + if json.Unmarshal(updated, &e) != nil || json.Unmarshal(e.Data, &d) != nil { + return line + } + rebuilt := object(rawEntry(e, d, updated, 0)) + if rebuilt == nil { + return line + } + // An event with no ID has an ID from its line number: keep it. + if uuid, ok := fields["uuid"]; ok { + rebuilt["uuid"] = uuid + } + return encodeJSON(rebuilt) +} + +// orderedStreams returns the keys of the raw session: main first, then the +// other streams by name. +func orderedStreams(raw map[string][]json.RawMessage) []string { + keys := make([]string, 0, len(raw)) + for key := range raw { + if key != mainLogKey { + keys = append(keys, key) + } + } + sort.Strings(keys) + if _, ok := raw[mainLogKey]; ok { + keys = append([]string{mainLogKey}, keys...) + } + return keys +} + +// binaryAsset is a session.binary_asset event: Copilot keeps each image that +// the model gets one time, by its digest, and refers to it by assetId. +type binaryAsset struct { + AssetID string `json:"assetId"` + MimeType string `json:"mimeType"` + Data string `json:"data"` +} + +// attachment is a file that the user attached to a message. A pasted or +// attached image has an image media type and an assetId, or its data. +type attachment struct { + AssetID string `json:"assetId"` + MimeType string `json:"mimeType"` + Data string `json:"data"` + Replaced json.RawMessage `json:"chainloop.replaced"` +} + +func (a attachment) isImage() bool { + return strings.HasPrefix(a.MimeType, "image/") +} + +// decodeImage decodes the base64 data of an image. When the image has an +// asset ID, the data must have that digest. +func decodeImage(encoded, assetID string) ([]byte, bool) { + data, err := base64.StdEncoding.DecodeString(encoded) + if err != nil || len(data) == 0 { + return nil, false + } + if assetID != "" && pointer.Digest(data) != assetID { + return nil, false + } + return data, true +} + +// userAttachments returns the attachments of a message of the user. A +// message of a subagent is the prompt of the parent agent, not of the user. +func userAttachments(e logEvent, data jsonObject) []attachment { + if e.Type != eventUserMessage || e.AgentID != "" { + return nil + } + var attachments []attachment + _ = json.Unmarshal(data["attachments"], &attachments) + return attachments +} + +// streamAssets returns the image assets of a stream that still hold their +// data, by asset ID. +func streamAssets(lines []json.RawMessage) map[string]binaryAsset { + assets := map[string]binaryAsset{} + for _, line := range lines { + e, _, ok := nativeEvent(line) + if !ok || e.Type != eventBinaryAsset { + continue + } + var a binaryAsset + if json.Unmarshal(e.Data, &a) == nil && a.AssetID != "" && a.Data != "" { + assets[a.AssetID] = a + } + } + return assets +} + +// PastedImages returns each distinct image that the user attached to a +// message. An image that a tool gave the model, such as a view of an image +// file, is not a pasted image (spec issue-3800 R-009). +func (p *Provider) PastedImages(raw map[string][]json.RawMessage) []trace.PastedImage { + var images []trace.PastedImage + seen := map[string]bool{} + position := 0 + for _, key := range orderedStreams(raw) { + lines := raw[key] + assets := streamAssets(lines) + for _, line := range lines { + e, data, ok := nativeEvent(line) + if !ok { + continue + } + for _, a := range userAttachments(e, data) { + if !a.isImage() { + continue + } + position++ + encoded := a.Data + if encoded == "" { + encoded = assets[a.AssetID].Data + } + img, valid := decodeImage(encoded, a.AssetID) + if !valid { + continue + } + digest := pointer.Digest(img) + if seen[digest] { + continue + } + seen[digest] = true + images = append(images, trace.PastedImage{ + Data: img, Digest: digest, MediaType: a.MimeType, Number: position, Timestamp: eventTimestamp(e.Timestamp), + }) + } + } + } + return images +} + +// streamCalls is what ReplaceSpecCopies learns from a stream before it +// changes it. +type streamCalls struct { + // tools holds the tool name of each tool call ID. + tools map[string]string + // succeeded holds the tool call IDs that completed with success. + succeeded map[string]bool + // pasted holds the asset IDs of the images that the user attached. + pasted map[string]bool + // args holds the arguments of each tool call ID. + args map[string]json.RawMessage + // cwd is the working folder of the session. + cwd string + // copies holds, for each shell tool call ID, the sources that the + // command read with cat. Only the output of that call can hold them. + copies map[string]sourceCopies +} + +func readStreamCalls(lines []json.RawMessage) streamCalls { + s := streamCalls{tools: map[string]string{}, succeeded: map[string]bool{}, pasted: map[string]bool{}, args: map[string]json.RawMessage{}} + for _, line := range lines { + e, data, ok := nativeEvent(line) + if !ok { + continue + } + switch e.Type { + case eventSessionStartRecord: + var start struct { + Context struct { + Cwd string `json:"cwd"` + } `json:"context"` + } + if json.Unmarshal(e.Data, &start) == nil && start.Context.Cwd != "" { + s.cwd = start.Context.Cwd + } + case eventAssistantMessage: + var requests []struct { + ToolCallID string `json:"toolCallId"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + } + _ = json.Unmarshal(data["toolRequests"], &requests) + for _, r := range requests { + if r.ToolCallID != "" { + s.tools[r.ToolCallID] = r.Name + s.args[r.ToolCallID] = r.Arguments + } + } + case eventToolComplete: + if completed(data) { + s.succeeded[jsonString(data["toolCallId"])] = true + } + case eventUserMessage: + for _, a := range userAttachments(e, data) { + if a.isImage() && a.AssetID != "" { + s.pasted[a.AssetID] = true + } + } + } + } + return s +} + +// completed reports whether a tool call completed with success. A shell +// command with an exit code other than 0 has success true, so the exit code +// is checked too. +func completed(data jsonObject) bool { + var status struct { + Success bool `json:"success"` + ShellExecution *struct { + ExitCode *int `json:"exitCode"` + } `json:"shellExecution"` + } + if json.Unmarshal(encodeJSON(data), &status) != nil || !status.Success { + return false + } + return status.ShellExecution == nil || status.ShellExecution.ExitCode == nil || *status.ShellExecution.ExitCode == 0 +} + +// ReplaceSpecCopies replaces each exact copy of a stored source with a pointer +// to its material: the full view or shell read of a source file, the text of +// a create call or of a patch that adds one file, and the data of an image +// that the user attached. Partial reads, changed content, failed tool calls, +// and data that cannot be decoded stay inline (spec issue-3800 R-009). +func (p *Provider) ReplaceSpecCopies(raw map[string][]json.RawMessage, sources pointer.Sources) pointer.Report { + report := pointer.Report{} + if len(sources) == 0 { + return report + } + for _, lines := range raw { + calls := readStreamCalls(lines) + calls.copies = commandSources(calls, sources) + images := storedImages(lines, calls.pasted, sources, report) + for i, line := range lines { + e, data, ok := nativeEvent(line) + if !ok { + continue + } + changed := false + switch e.Type { + case eventBinaryAsset: + changed = replaceAsset(data, images, report) + case eventUserMessage: + changed = replaceAttachments(e, data, images, sources, report) + case eventToolComplete: + changed = replaceRead(data, calls, sources, report) + case eventAssistantMessage: + changed = replaceWrites(data, calls, sources, report) + case eventHookStart: + changed = replaceHookInput(data, calls, sources, report) + } + if changed { + lines[i] = updateEvent(line, data) + } + } + } + return report +} + +// storedImages returns the material of each pasted image asset that is +// stored, by asset ID. It counts the assets that stay inline. +func storedImages(lines []json.RawMessage, pasted map[string]bool, sources pointer.Sources, report pointer.Report) map[string]string { + images := map[string]string{} + for id, asset := range streamAssets(lines) { + if !pasted[id] { + continue + } + res := report.Finder(pointer.FinderPastedImage) + if _, ok := decodeImage(asset.Data, id); !ok { + res.Skip(pointer.ReasonInvalidImage, 1) + continue + } + material, ok := sources[id] + if !ok { + res.Skip(pointer.ReasonMaterialNotStored, 1) + continue + } + images[id] = material + } + return images +} + +// replaceAsset replaces the data of a stored pasted image with a pointer. +func replaceAsset(data jsonObject, images map[string]string, report pointer.Report) bool { + material, ok := images[jsonString(data["assetId"])] + if !ok || len(data[dataField]) == 0 { + return false + } + res := report.Finder(pointer.FinderPastedImage) + res.Replaced++ + res.BytesRemoved += len(data[dataField]) + delete(data, dataField) + data[pointer.Marker] = pointer.New(material) + return true +} + +// replaceAttachments marks each stored image attachment with its pointer, so +// that the viewer shows it, and replaces the data of an attachment that holds +// its image. +func replaceAttachments(e logEvent, data jsonObject, images map[string]string, sources pointer.Sources, report pointer.Report) bool { + var attachments []jsonObject + if userAttachments(e, data) == nil || json.Unmarshal(data["attachments"], &attachments) != nil { + return false + } + changed := false + for _, fields := range attachments { + var a attachment + if json.Unmarshal(encodeJSON(fields), &a) != nil || !a.isImage() || len(a.Replaced) > 0 { + continue + } + if a.Data != "" { + res := report.Finder(pointer.FinderPastedImage) + img, ok := decodeImage(a.Data, a.AssetID) + if !ok { + res.Skip(pointer.ReasonInvalidImage, 1) + continue + } + material, ok := sources[pointer.Digest(img)] + if !ok { + res.Skip(pointer.ReasonMaterialNotStored, 1) + continue + } + res.Replaced++ + res.BytesRemoved += len(fields[dataField]) + delete(fields, dataField) + fields[pointer.Marker] = pointer.New(material) + changed = true + continue + } + if material, ok := images[a.AssetID]; ok { + fields[pointer.Marker] = pointer.New(material) + changed = true + } + } + if changed { + data["attachments"] = encodeJSON(attachments) + } + return changed +} + +// splitShellResult returns the output of a successful shell command with the +// newline before the status line dropped, and the offset of the status line. +// It returns false when the command failed or the status is not known. +// Copilot drops the last newline of the output, so the caller tries the +// output with and without it. +func splitShellResult(content string) (string, int, bool) { + m := shellEnvelope.FindStringSubmatchIndex(content) + if m == nil || content[m[6]:m[7]] != "0" { + return "", 0, false + } + return content[m[2]:m[3]], m[4], true +} + +// readReplacement returns what replaces the result text of a tool call that +// holds copies of sources, and the number of copies. A full view of a source, +// or a shell output that is exactly a source, becomes one pointer. A shell +// output that holds sources that the same command read with cat becomes text +// and pointer blocks. A view with a line range is a partial read, so it stays +// inline, also when the range covers the whole file. +func readReplacement(tool string, args json.RawMessage, copies sourceCopies, content string, sources pointer.Sources) (json.RawMessage, int) { + switch { + case tool == viewTool: + if _, ranged := object(args)["view_range"]; ranged { + return nil, 0 + } + if material, ok := sources[pointer.Digest([]byte(content))]; content != "" && ok { + return pointer.New(material), 1 + } + case slices.Contains(commandTools, tool): + output, status, ok := splitShellResult(content) + if !ok { + return nil, 0 + } + for _, candidate := range []string{output, output + "\n"} { + if material, ok := sources[pointer.Digest([]byte(candidate))]; candidate != "" && ok { + return pointer.New(material), 1 + } + } + // The text before the status line keeps its last newline, so that a + // source at the end of the output ends at a line boundary. The status + // line stays after the blocks of the output. + if blocks, n := replaceTextCopies(content[:status], copies); n > 0 { + blocks = append(blocks, encodeJSON(trace.RawSessionTextBlock{Type: textBlock, Text: content[status:]})) + return encodeJSON(blocks), n + } + } + return nil, 0 +} + +// replaceRead replaces the copies of sources in the result of a read. +func replaceRead(data jsonObject, calls streamCalls, sources pointer.Sources, report pointer.Report) bool { + id := jsonString(data["toolCallId"]) + result := object(data[resultField]) + if result == nil || len(result[pointer.Marker]) > 0 || !calls.succeeded[id] { + return false + } + replacement, n := readReplacement(calls.tools[id], calls.args[id], calls.copies[id], jsonString(result["content"]), sources) + if n == 0 { + return false + } + res := report.Finder(pointer.FinderFileRead) + res.Replaced += n + res.BytesRemoved += len(result["content"]) + len(result["detailedContent"]) + // detailedContent is the same read, shown as a diff. + delete(result, "content") + delete(result, "detailedContent") + result[pointer.Marker] = replacement + data[resultField] = encodeJSON(result) + return true +} + +// sourceCopies maps the text of a source that a shell command read to its +// material. +type sourceCopies map[string]string + +// maxSourceBytes is the size limit of a file that a shell command read, the +// same limit as for a local spec source. +const maxSourceBytes = 1 << 20 + +// catCommand finds each cat command in a shell command line. +var catCommand = regexp.MustCompile(`(?:^|[\s;&|()$` + "`" + `])cat(?:\s|$)`) + +// catPaths returns the file operands of each cat command in a shell command +// line, in order. Options are skipped. An operand list ends at a shell +// operator or a redirection. +func catPaths(command string) []string { + var paths []string + for _, loc := range catCommand.FindAllStringIndex(command, -1) { + rest := command[loc[1]:] + for { + rest = strings.TrimLeft(rest, " \t") + if rest == "" || strings.ContainsRune(";&|()<>\n`", rune(rest[0])) { + break + } + var operand string + switch rest[0] { + case '"', '\'': + end := strings.IndexByte(rest[1:], rest[0]) + if end < 0 { + rest = "" + continue + } + operand, rest = rest[1:end+1], rest[end+2:] + default: + end := strings.IndexAny(rest, " \t;&|()<>\n`\"'") + if end < 0 { + end = len(rest) + } + operand, rest = rest[:end], rest[end:] + } + if operand != "" && !strings.HasPrefix(operand, "-") { + paths = append(paths, operand) + } + } + } + return paths +} + +// commandSources reads, for each shell tool call, the files that its command +// read with cat, and keeps those that are stored sources. The file is read at +// the push, so a file that changed after the session matches no source and +// stays inline. +func commandSources(calls streamCalls, sources pointer.Sources) map[string]sourceCopies { + all := map[string]sourceCopies{} + for id, tool := range calls.tools { + if !slices.Contains(commandTools, tool) { + continue + } + copies := sourceCopies{} + for _, path := range catPaths(jsonString(object(calls.args[id])["command"])) { + if !filepath.IsAbs(path) { + if !filepath.IsAbs(calls.cwd) { + continue + } + path = filepath.Join(calls.cwd, path) + } + data, ok := readSmallFile(path) + if !ok { + continue + } + if material, ok := sources[pointer.Digest(data)]; ok { + copies[string(data)] = material + } + } + if len(copies) > 0 { + all[id] = copies + } + } + return all +} + +// readSmallFile reads a regular, non-empty file of up to maxSourceBytes. +func readSmallFile(path string) ([]byte, bool) { + f, err := os.Open(path) + if err != nil { + return nil, false + } + defer f.Close() + info, err := f.Stat() + if err != nil || !info.Mode().IsRegular() || info.Size() == 0 || info.Size() > maxSourceBytes { + return nil, false + } + data, err := io.ReadAll(io.LimitReader(f, maxSourceBytes+1)) + if err != nil || len(data) == 0 || len(data) > maxSourceBytes { + return nil, false + } + return data, true +} + +// replaceTextCopies splits text into text blocks and pointer blocks, one +// pointer for each copy of a source. A copy must start at the start of a line +// and end at the end of a line. +func replaceTextCopies(text string, copies sourceCopies) ([]json.RawMessage, int) { + // The longest source first, so that overlapping sources give one result. + keys := make([]string, 0, len(copies)) + for source := range copies { + keys = append(keys, source) + } + sort.Slice(keys, func(i, j int) bool { + if len(keys[i]) == len(keys[j]) { + return keys[i] < keys[j] + } + return len(keys[i]) > len(keys[j]) + }) + var blocks []json.RawMessage + n := 0 + for text != "" { + position, matched := -1, "" + for _, source := range keys { + if index := sourceOffset(text, source); index >= 0 && (position < 0 || index < position) { + position, matched = index, source + } + } + if position < 0 { + blocks = append(blocks, encodeJSON(trace.RawSessionTextBlock{Type: textBlock, Text: text})) + break + } + if position > 0 { + blocks = append(blocks, encodeJSON(trace.RawSessionTextBlock{Type: textBlock, Text: text[:position]})) + } + blocks = append(blocks, pointer.New(copies[matched])) + text = text[position+len(matched):] + n++ + } + if n == 0 { + return nil, 0 + } + return blocks, n +} + +// sourceOffset returns the offset of the first copy of source in text that +// starts and ends at line boundaries, or -1. +func sourceOffset(text, source string) int { + if source == "" { + return -1 + } + for start := 0; start < len(text); { + rel := strings.Index(text[start:], source) + if rel < 0 { + return -1 + } + index := start + rel + end := index + len(source) + if (index == 0 || text[index-1] == '\n') && (end == len(text) || strings.HasSuffix(source, "\n") || text[end] == '\n') { + return index + } + start = index + 1 + } + return -1 +} + +// replaceWriteArgs returns the arguments of a create call, or of a patch that +// adds one file, with the text that is an exact copy of a source replaced +// with a pointer. +func replaceWriteArgs(tool string, args json.RawMessage, sources pointer.Sources, report pointer.Report) (json.RawMessage, bool) { + switch tool { + case createTool: + fields := object(args) + if fields == nil || len(fields["file_text"]) == 0 { + return nil, false + } + material, ok := sources[pointer.Digest([]byte(jsonString(fields["file_text"])))] + if !ok { + return nil, false + } + report.Finder(pointer.FinderFileWrite).BytesRemoved += len(fields["file_text"]) + delete(fields, "file_text") + fields[pointer.Marker] = pointer.New(material) + args = encodeJSON(fields) + case toolApplyPatch: + // The patch is a JSON string, or an object with an input field, as + // ReadHookInput reads it. + path, content, ok := addedFile(patchText(args)) + if !ok { + return nil, false + } + material, ok := sources[pointer.Digest([]byte(content))] + if !ok { + return nil, false + } + report.Finder(pointer.FinderFileWrite).BytesRemoved += len(args) + args = encodeJSON(jsonObject{"path": encodeJSON(path), pointer.Marker: pointer.New(material)}) + default: + return nil, false + } + report.Finder(pointer.FinderFileWrite).Replaced++ + return args, true +} + +// replaceWrites replaces the text of each successful create call, or patch +// that adds one file, that is an exact copy of a source. +func replaceWrites(data jsonObject, calls streamCalls, sources pointer.Sources, report pointer.Report) bool { + var requests []jsonObject + if json.Unmarshal(data["toolRequests"], &requests) != nil { + return false + } + changed := false + for _, req := range requests { + if !calls.succeeded[jsonString(req["toolCallId"])] { + continue + } + if args, ok := replaceWriteArgs(jsonString(req["name"]), req["arguments"], sources, report); ok { + req["arguments"] = args + changed = true + } + } + if changed { + data["toolRequests"] = encodeJSON(requests) + } + return changed +} + +// replaceHookInput replaces the copies in the input of a Trace hook, which +// Copilot logs in a hook.start event: the tool arguments of a preToolUse +// batch, and the arguments and the result text of a postToolUse call. The +// same rules apply as for the tool events. +func replaceHookInput(data jsonObject, calls streamCalls, sources pointer.Sources, report pointer.Report) bool { + input := object(data["input"]) + if input == nil { + return false + } + changed := false + switch jsonString(data["hookType"]) { + case "preToolUse": + var batch []jsonObject + if json.Unmarshal(input["toolCalls"], &batch) != nil { + return false + } + for _, call := range batch { + if !calls.succeeded[jsonString(call["id"])] { + continue + } + if args, ok := replaceWriteArgs(jsonString(call["name"]), call["args"], sources, report); ok { + call["args"] = args + changed = true + } + } + if changed { + input["toolCalls"] = encodeJSON(batch) + } + case "postToolUse": + id := jsonString(input["toolCallId"]) + if !calls.succeeded[id] { + return false + } + tool := jsonString(input["toolName"]) + if args, ok := replaceWriteArgs(tool, input["toolArgs"], sources, report); ok { + input["toolArgs"] = args + changed = true + } + result := object(input["toolResult"]) + if result != nil && len(result[pointer.Marker]) == 0 { + if replacement, n := readReplacement(tool, input["toolArgs"], calls.copies[id], jsonString(result["textResultForLlm"]), sources); n > 0 { + res := report.Finder(pointer.FinderFileRead) + res.Replaced += n + res.BytesRemoved += len(result["textResultForLlm"]) + delete(result, "textResultForLlm") + result[pointer.Marker] = replacement + input["toolResult"] = encodeJSON(result) + changed = true + } + } + } + if changed { + data["input"] = encodeJSON(input) + } + return changed +} + +// addedFile returns the path and the content of a patch that adds exactly one +// file. Other patches change content that the patch does not hold, so they +// stay inline. +func addedFile(patch string) (string, string, bool) { + lines := strings.Split(strings.TrimSuffix(patch, "\n"), "\n") + if len(lines) < 4 || lines[0] != "*** Begin Patch" || !strings.HasPrefix(lines[1], "*** Add File: ") || lines[len(lines)-1] != "*** End Patch" { + return "", "", false + } + var content strings.Builder + for _, line := range lines[2 : len(lines)-1] { + text, ok := strings.CutPrefix(line, "+") + if !ok { + return "", "", false + } + content.WriteString(text) + content.WriteByte('\n') + } + return strings.TrimPrefix(lines[1], "*** Add File: "), content.String(), true +} diff --git a/app/cli/internal/trace/copilot/materials_test.go b/app/cli/internal/trace/copilot/materials_test.go new file mode 100644 index 000000000..df2e30dfb --- /dev/null +++ b/app/cli/internal/trace/copilot/materials_test.go @@ -0,0 +1,438 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//nolint:goconst // Keep native event literals readable in regression fixtures. +package copilot + +import ( + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pointer" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + testSource = "# Task\n\nBuild the requested feature.\n" + testMaterial = "sha256:stored-redacted-source" + testCallID = "call-1" + toolView = "view" +) + +func toJSON(t *testing.T, v any) string { + t.Helper() + raw, err := json.Marshal(v) + require.NoError(t, err) + return string(raw) +} + +// toolExchange is the assistant message with one tool request and its +// completion, as Copilot writes them. +func toolExchange(t *testing.T, tool string, args any, result map[string]any) []string { + t.Helper() + request := toJSON(t, map[string]any{ + "type": eventAssistantMessage, "id": "a1", "timestamp": "2026-04-07T21:00:01Z", + "data": map[string]any{"content": "", "toolRequests": []map[string]any{{"toolCallId": testCallID, "name": tool, "arguments": args}}}, + }) + result["toolCallId"] = testCallID + complete := toJSON(t, map[string]any{"type": eventToolComplete, "id": "t1", "timestamp": "2026-04-07T21:00:02Z", "data": result}) + return []string{request, complete} +} + +// rawSession parses the event log lines, as the push does, and returns the +// raw session of the evidence. +func rawSession(t *testing.T, lines ...string) map[string][]json.RawMessage { + t.Helper() + d, err := parseLog(t, header+"\n"+strings.Join(lines, "\n")+"\n") + require.NoError(t, err) + return d.RawSession +} + +func success(content string) map[string]any { + return map[string]any{"success": true, "result": map[string]any{"content": content, "detailedContent": "diff --git a/x b/x\n" + content}} +} + +func TestReplaceSpecCopies(t *testing.T) { + patch := "*** Begin Patch\n*** Add File: ticket.md\n+# Task\n+\n+Build the requested feature.\n*** End Patch\n" + tests := []struct { + name string + tool string + args any + result map[string]any + finder string + }{ + {name: "full view", tool: toolView, args: map[string]any{"path": "/r/ticket.md"}, result: success(testSource), finder: pointer.FinderFileRead}, + {name: "partial view", tool: toolView, args: map[string]any{"path": "/r/ticket.md", "view_range": []int{1, 1}}, result: success("# Task\n")}, + {name: "ranged view of the whole file", tool: toolView, args: map[string]any{"path": "/r/ticket.md", "view_range": []int{1, -1}}, result: success(testSource)}, + {name: "failed view", tool: toolView, args: map[string]any{"path": "/r/ticket.md"}, result: map[string]any{"success": false, "result": map[string]any{"content": testSource}}}, + {name: "shell read", tool: toolBash, args: map[string]any{"command": "cat ticket.md"}, result: success(strings.TrimSuffix(testSource, "\n") + "\n"), finder: pointer.FinderFileRead}, + {name: "older shell envelope", tool: toolBash, args: map[string]any{"command": "cat ticket.md"}, result: success(testSource + ""), finder: pointer.FinderFileRead}, + {name: "failed shell", tool: toolBash, args: map[string]any{"command": "cat ticket.md"}, result: success(testSource + "")}, + {name: "failed shell with exit code field", tool: toolBash, args: map[string]any{"command": "cat ticket.md"}, result: map[string]any{"success": true, "shellExecution": map[string]any{"exitCode": 2}, "result": map[string]any{"content": testSource + ""}}}, + {name: "changed content", tool: toolView, args: map[string]any{"path": "/r/ticket.md"}, result: success(testSource + "more\n")}, + {name: "other tool", tool: "glob", args: map[string]any{"pattern": "*"}, result: success(testSource)}, + {name: "create", tool: toolCreate, args: map[string]any{"path": "/r/ticket.md", "file_text": testSource}, result: success("Created file"), finder: pointer.FinderFileWrite}, + {name: "failed create", tool: toolCreate, args: map[string]any{"path": "/r/ticket.md", "file_text": testSource}, result: map[string]any{"success": false, "result": map[string]any{"content": "exists"}}}, + {name: "patch creation", tool: toolApplyPatch, args: patch, result: success("Added 1 file(s)"), finder: pointer.FinderFileWrite}, + {name: "patch update", tool: toolApplyPatch, args: strings.Replace(patch, "Add File", "Update File", 1), result: success("Updated")}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + raw := rawSession(t, toolExchange(t, tc.tool, tc.args, tc.result)...) + before := toJSON(t, raw) + sources := pointer.Sources{pointer.Digest([]byte(testSource)): testMaterial} + + report := New().ReplaceSpecCopies(raw, sources) + after := toJSON(t, raw) + if tc.finder == "" { + assert.Equal(t, before, after) + return + } + require.NotNil(t, report[tc.finder]) + assert.Equal(t, 1, report[tc.finder].Replaced) + assert.NotContains(t, after, "Build the requested feature.") + assert.Equal(t, 1, viewerPointers(t, raw["main"], testMaterial), "the viewer message shows the pointer") + + // A second assembly changes nothing. + New().ReplaceSpecCopies(raw, sources) + assert.Equal(t, after, toJSON(t, raw)) + }) + } +} + +// hookRecords are the hook.start events that Copilot writes for the Trace +// hooks of one tool call: the preToolUse batch and the postToolUse call. +func hookRecords(t *testing.T, tool string, args any, resultType, text string) []string { + t.Helper() + pre := toJSON(t, map[string]any{ + "type": eventHookStart, "id": "h1", "timestamp": "2026-04-07T21:00:01Z", + "data": map[string]any{"hookInvocationId": "i1", "hookType": "preToolUse", "input": map[string]any{ + "sessionId": testSessionID, "toolCalls": []map[string]any{{"id": testCallID, "name": tool, "args": args}}, + }}, + }) + post := toJSON(t, map[string]any{ + "type": eventHookStart, "id": "h2", "timestamp": "2026-04-07T21:00:02Z", + "data": map[string]any{"hookInvocationId": "i2", "hookType": "postToolUse", "input": map[string]any{ + "sessionId": testSessionID, "toolCallId": testCallID, "toolName": tool, "toolArgs": args, + "toolResult": map[string]any{"resultType": resultType, "textResultForLlm": text}, + }}, + }) + return []string{pre, post} +} + +func TestReplaceHookCopies(t *testing.T) { + tests := []struct { + name string + tool string + args any + result map[string]any + resultType string + text string + want map[string]int + }{ + { + name: "full view", tool: toolView, args: map[string]any{"path": "/r/ticket.md"}, + result: success(testSource), resultType: "success", text: testSource, + want: map[string]int{pointer.FinderFileRead: 2}, + }, + { + name: "create", tool: toolCreate, args: map[string]any{"path": "/r/ticket.md", "file_text": testSource}, + result: success("Created file"), resultType: "success", text: "Created file", + want: map[string]int{pointer.FinderFileWrite: 3}, + }, + { + // The hook payload can carry the patch of apply_patch in an + // object, as hooks.go reads it. + name: "patch creation in object form", tool: toolApplyPatch, + args: map[string]any{"input": "*** Begin Patch\n*** Add File: ticket.md\n+# Task\n+\n+Build the requested feature.\n*** End Patch\n"}, + result: success("Added 1 file(s)"), resultType: "success", text: "Added 1 file(s)", + want: map[string]int{pointer.FinderFileWrite: 3}, + }, + { + name: "failed view", tool: toolView, args: map[string]any{"path": "/r/ticket.md"}, + result: map[string]any{"success": false, "result": map[string]any{"content": testSource}}, resultType: "failure", text: testSource, + }, + { + name: "ranged view", tool: toolView, args: map[string]any{"path": "/r/ticket.md", "view_range": []int{1, -1}}, + result: success(testSource), resultType: "success", text: testSource, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + exchange := toolExchange(t, tc.tool, tc.args, tc.result) + hooks := hookRecords(t, tc.tool, tc.args, tc.resultType, tc.text) + raw := rawSession(t, exchange[0], hooks[0], hooks[1], exchange[1]) + before := toJSON(t, raw) + sources := pointer.Sources{pointer.Digest([]byte(testSource)): testMaterial} + + report := New().ReplaceSpecCopies(raw, sources) + after := toJSON(t, raw) + if tc.want == nil { + assert.Equal(t, before, after) + return + } + for finder, n := range tc.want { + require.NotNil(t, report[finder]) + assert.Equal(t, n, report[finder].Replaced, finder) + } + assert.NotContains(t, after, "Build the requested feature.") + + New().ReplaceSpecCopies(raw, sources) + assert.Equal(t, after, toJSON(t, raw)) + }) + } +} + +func TestReplaceCombinedShellReads(t *testing.T) { + repo := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(repo, "docs"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(repo, "docs", "ticket.md"), []byte(testSource), 0o600)) + require.NoError(t, os.WriteFile(filepath.Join(repo, "other.md"), []byte("other text\n"), 0o600)) + start := toJSON(t, map[string]any{ + "type": eventSessionStartRecord, "id": "s", "timestamp": "2026-04-07T21:00:00Z", + "data": map[string]any{"sessionId": testSessionID, "context": map[string]any{"cwd": repo}}, + }) + envelope := "" + + tests := []struct { + name string + command string + output string + want bool + }{ + {name: "two files", command: "cat docs/ticket.md && cat other.md", output: "?? x\n" + testSource + "other text\n" + envelope, want: true}, + {name: "quoted path", command: "git status && cat 'docs/ticket.md'", output: "clean\n" + testSource + envelope, want: true}, + {name: "several operands", command: "cat other.md docs/ticket.md", output: "other text\n" + testSource + envelope, want: true}, + {name: "options before the operands", command: "cat -- other.md \"docs/ticket.md\" | tee /dev/null", output: "other text\n" + testSource + envelope, want: true}, + {name: "source inside a line", command: "cat docs/ticket.md", output: "prefix " + testSource + envelope}, + {name: "file not read with cat", command: "head -n 9 docs/ticket.md && echo", output: "x\n" + testSource + envelope}, + {name: "failed command", command: "cat docs/ticket.md && false", output: "x\n" + testSource + ""}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + exchange := toolExchange(t, toolBash, map[string]any{"command": tc.command}, success(tc.output)) + hooks := hookRecords(t, toolBash, map[string]any{"command": tc.command}, "success", tc.output) + // The test log has its own session.start, with the working folder. + d, err := parseLog(t, strings.Replace(header+"\n", header, start, 1)+strings.Join([]string{exchange[0], hooks[0], hooks[1], exchange[1]}, "\n")+"\n") + require.NoError(t, err) + raw := d.RawSession + before := toJSON(t, raw) + + New().ReplaceSpecCopies(raw, pointer.Sources{pointer.Digest([]byte(testSource)): testMaterial}) + after := toJSON(t, raw) + if !tc.want { + assert.Equal(t, before, after) + return + } + assert.NotContains(t, after, "Build the requested feature.") + // The text around the copy, and the status line, stay. + assert.Contains(t, after, "completed with exit code 0") + assert.Contains(t, after, strings.Split(tc.output, "\n")[0]) + assert.Equal(t, 1, viewerPointers(t, raw["main"], testMaterial)) + + New().ReplaceSpecCopies(raw, pointer.Sources{pointer.Digest([]byte(testSource)): testMaterial}) + assert.Equal(t, after, toJSON(t, raw)) + }) + } +} + +// TestCatCopiesPerCall checks that the cat of one shell call does not let the +// output of another call, which read no file, be replaced. +func TestCatCopiesPerCall(t *testing.T) { + repo := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(repo, "ticket.md"), []byte(testSource), 0o600)) + start := toJSON(t, map[string]any{ + "type": eventSessionStartRecord, "id": "s", "timestamp": "2026-04-07T21:00:00Z", + "data": map[string]any{"sessionId": testSessionID, "context": map[string]any{"cwd": repo}}, + }) + call := func(id, command, output string) []string { + request := toJSON(t, map[string]any{ + "type": eventAssistantMessage, "id": "a-" + id, "timestamp": "2026-04-07T21:00:01Z", + "data": map[string]any{"toolRequests": []map[string]any{{"toolCallId": id, "name": toolBash, "arguments": map[string]any{"command": command}}}}, + }) + result := success(output) + result["toolCallId"] = id + complete := toJSON(t, map[string]any{"type": eventToolComplete, "id": "t-" + id, "timestamp": "2026-04-07T21:00:02Z", "data": result}) + return []string{request, complete} + } + envelope := "" + lines := append(call("c1", "git status && cat ticket.md", "clean\n"+testSource+envelope), + call("c2", "./generate.sh", "generated\n"+testSource+envelope)...) + d, err := parseLog(t, start+"\n"+strings.Join(lines, "\n")+"\n") + require.NoError(t, err) + + report := New().ReplaceSpecCopies(d.RawSession, pointer.Sources{pointer.Digest([]byte(testSource)): testMaterial}) + require.NotNil(t, report[pointer.FinderFileRead]) + assert.Equal(t, 1, report[pointer.FinderFileRead].Replaced) + assert.Equal(t, 1, viewerPointers(t, d.RawSession["main"], testMaterial)) + assert.Contains(t, toJSON(t, d.RawSession), "generated\\n# Task") +} + +func TestCatPaths(t *testing.T) { + tests := []struct { + command string + want []string + }{ + {command: "cat a.md", want: []string{"a.md"}}, + {command: "cat a.md b.md && cat 'c d.md'", want: []string{"a.md", "b.md", "c d.md"}}, + {command: "cat -n -- \"a.md\" | head", want: []string{"a.md"}}, + {command: "test \"$(cat x.txt)\" = y", want: []string{"x.txt"}}, + {command: "cat b.md", want: nil}, + {command: "concat a.md && bobcat b.md", want: nil}, + } + for _, tc := range tests { + t.Run(tc.command, func(t *testing.T) { + assert.Equal(t, tc.want, catPaths(tc.command)) + }) + } +} + +// viewerPointers counts the viewer messages, outside source_event, that hold +// a pointer to the material. +func viewerPointers(t *testing.T, lines []json.RawMessage, material string) int { + t.Helper() + n := 0 + for _, line := range lines { + var entry trace.RawSessionEntry + if json.Unmarshal(line, &entry) != nil || len(entry.Message.Content) == 0 { + continue + } + if strings.Contains(string(entry.Message.Content), string(pointer.New(material))) { + n++ + } + } + return n +} + +var testImage = []byte("\x89PNG test image bytes") + +func assetEvent(t *testing.T, id string, data []byte) string { + t.Helper() + return toJSON(t, map[string]any{ + "type": eventBinaryAsset, "id": "asset-" + id, "timestamp": "2026-04-07T21:00:00Z", + "data": map[string]any{"assetId": id, "type": "image", "mimeType": "image/png", "byteLength": len(data), "data": base64.StdEncoding.EncodeToString(data)}, + }) +} + +func pastedMessage(t *testing.T, assetIDs ...string) string { + t.Helper() + attachments := make([]map[string]any, 0, len(assetIDs)) + for _, id := range assetIDs { + attachments = append(attachments, map[string]any{"type": "file", "path": "/tmp/pasted.png", "displayName": "pasted.png", "assetId": id, "mimeType": "image/png"}) + } + return toJSON(t, map[string]any{ + "type": eventUserMessage, "id": "u1", "timestamp": "2026-04-07T21:00:00.500Z", + "data": map[string]any{"content": "What color is it?", "attachments": attachments}, + }) +} + +// toolImage is a view of an image file: its asset is in a tool result, not +// in a user message. +func toolImage(t *testing.T, id string) []string { + t.Helper() + return toolExchange(t, toolView, map[string]any{"path": "/r/media.png"}, map[string]any{ + "success": true, + "result": map[string]any{"content": "Viewed image file successfully.", "binaryResultsForLlm": []map[string]any{{"type": "image", "assetId": id, "mimeType": "image/png"}}}, + }) +} + +func TestPastedImages(t *testing.T) { + digest := pointer.Digest(testImage) + other := []byte("\x89PNG another image") + otherDigest := pointer.Digest(other) + + tests := []struct { + name string + lines []string + want []trace.PastedImage + }{ + { + name: "one image pasted twice", + lines: []string{assetEvent(t, digest, testImage), pastedMessage(t, digest, digest)}, + want: []trace.PastedImage{{Data: testImage, Digest: digest, MediaType: "image/png", Number: 1, Timestamp: "2026-04-07T21:00:00Z"}}, + }, + { + name: "two images", + lines: []string{assetEvent(t, digest, testImage), assetEvent(t, otherDigest, other), pastedMessage(t, digest, otherDigest)}, + want: []trace.PastedImage{ + {Data: testImage, Digest: digest, MediaType: "image/png", Number: 1, Timestamp: "2026-04-07T21:00:00Z"}, + {Data: other, Digest: otherDigest, MediaType: "image/png", Number: 2, Timestamp: "2026-04-07T21:00:00Z"}, + }, + }, + { + name: "image of a tool result", + lines: append([]string{assetEvent(t, digest, testImage)}, toolImage(t, digest)...), + }, + { + name: "data that cannot be decoded", + lines: []string{strings.Replace(assetEvent(t, digest, testImage), base64.StdEncoding.EncodeToString(testImage), "%%%", 1), pastedMessage(t, digest)}, + }, + { + name: "data that does not match its asset ID", + lines: []string{assetEvent(t, otherDigest, testImage), pastedMessage(t, otherDigest)}, + }, + { + name: "asset with no data", + lines: []string{pastedMessage(t, digest)}, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, New().PastedImages(rawSession(t, tc.lines...))) + }) + } +} + +func TestReplacePastedImages(t *testing.T) { + digest := pointer.Digest(testImage) + media := []byte("\x89PNG media file") + mediaDigest := pointer.Digest(media) + encoded := base64.StdEncoding.EncodeToString(testImage) + + lines := append([]string{assetEvent(t, digest, testImage), pastedMessage(t, digest, digest), assetEvent(t, mediaDigest, media)}, toolImage(t, mediaDigest)...) + + t.Run("stored image", func(t *testing.T) { + raw := rawSession(t, lines...) + // The media file is a source too, but the agent read it with a tool: + // it stays inline. + sources := pointer.Sources{digest: "sha256:image-material", mediaDigest: "sha256:media-material"} + report := New().ReplaceSpecCopies(raw, sources) + + after := toJSON(t, raw) + assert.NotContains(t, after, encoded) + assert.Contains(t, after, base64.StdEncoding.EncodeToString(media)) + require.NotNil(t, report[pointer.FinderPastedImage]) + assert.Equal(t, 1, report[pointer.FinderPastedImage].Replaced) + assert.Equal(t, 1, viewerPointers(t, raw["main"], "sha256:image-material"), "the user message shows the image pointer") + + New().ReplaceSpecCopies(raw, sources) + assert.Equal(t, after, toJSON(t, raw)) + }) + + t.Run("image not stored", func(t *testing.T) { + raw := rawSession(t, lines...) + before := toJSON(t, raw) + report := New().ReplaceSpecCopies(raw, pointer.Sources{"sha256:unrelated": "sha256:x"}) + assert.Equal(t, before, toJSON(t, raw)) + require.NotNil(t, report[pointer.FinderPastedImage]) + assert.Equal(t, 1, report[pointer.FinderPastedImage].Skipped[pointer.ReasonMaterialNotStored]) + }) +} diff --git a/app/cli/internal/trace/copilot/parse.go b/app/cli/internal/trace/copilot/parse.go index d6ab58afc..d5bdaec2c 100644 --- a/app/cli/internal/trace/copilot/parse.go +++ b/app/cli/internal/trace/copilot/parse.go @@ -17,6 +17,7 @@ package copilot import ( "bufio" + "bytes" "context" "encoding/json" "errors" @@ -39,6 +40,9 @@ const ( eventToolComplete = "tool.execution_complete" eventUsageRecord = "session.usage_record" eventShutdown = "session.shutdown" + eventSkillInvoked = "skill.invoked" + eventBinaryAsset = "session.binary_asset" + eventHookStart = "hook.start" // modelProvider is the vendor of the models as Trace records it: Copilot // routes requests to models of several vendors. @@ -113,7 +117,13 @@ type eventData struct { } `json:"toolRequests"` Result *struct { Content string `json:"content"` + // Replaced is the pointer that replaced Content (spec issue-3800 R-009). + Replaced json.RawMessage `json:"chainloop.replaced"` } `json:"result"` + Attachments []struct { + // Replaced is the pointer to the stored image of the attachment. + Replaced json.RawMessage `json:"chainloop.replaced"` + } `json:"attachments"` Usage *copilotUsage `json:"usage"` CurrentModel string `json:"currentModel"` ModelMetrics map[string]struct { @@ -464,14 +474,19 @@ func rawEntry(e logEvent, data eventData, raw json.RawMessage, line int) json.Ra switch e.Type { case eventUserMessage: entry.Type = trace.RoleUser - blocks = append(blocks, trace.RawSessionTextBlock{Type: "text", Text: data.Content}) + blocks = append(blocks, trace.RawSessionTextBlock{Type: textBlock, Text: data.Content}) + for _, a := range data.Attachments { + if len(a.Replaced) > 0 { + blocks = append(blocks, map[string]json.RawMessage{"type": json.RawMessage(`"image"`), "source": a.Replaced}) + } + } case eventAssistantMessage: entry.Type = trace.RoleAssistant if data.ReasoningText != "" { blocks = append(blocks, map[string]string{"type": "thinking", "thinking": data.ReasoningText}) } if data.Content != "" { - blocks = append(blocks, trace.RawSessionTextBlock{Type: "text", Text: data.Content}) + blocks = append(blocks, trace.RawSessionTextBlock{Type: textBlock, Text: data.Content}) } for _, req := range data.ToolRequests { blocks = append(blocks, trace.RawSessionToolUseBlock{Type: "tool_use", ID: req.ToolCallID, Name: req.Name, Input: toolInput(req.Arguments)}) @@ -483,6 +498,14 @@ func rawEntry(e logEvent, data eventData, raw json.RawMessage, line int) json.Ra content = data.Result.Content } encoded, _ := json.Marshal(content) + if data.Result != nil && len(data.Result.Replaced) > 0 { + // A pointer, or text and pointer blocks for a shell output that + // holds copies of sources. + encoded = data.Result.Replaced + if !bytes.HasPrefix(bytes.TrimSpace(encoded), []byte("[")) { + encoded, _ = json.Marshal([]json.RawMessage{data.Result.Replaced}) + } + } blocks = append(blocks, trace.RawSessionToolResultBlock{Type: "tool_result", ToolUseID: data.ToolCallID, Content: encoded}) default: return raw diff --git a/app/cli/internal/trace/copilot/skills.go b/app/cli/internal/trace/copilot/skills.go new file mode 100644 index 000000000..48842c29e --- /dev/null +++ b/app/cli/internal/trace/copilot/skills.go @@ -0,0 +1,202 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package copilot + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/skill" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" +) + +var _ trace.SkillTracker = (*Provider)(nil) + +// mainLogKey is the key of the event log in the skill scan offsets. Copilot +// writes one log for each session, subagents included. +const mainLogKey = "main" + +// SessionSkills reads the skills from the private copy of the event log. Only +// a skill.invoked event counts as a use: Copilot writes it when it loads a +// skill into the session, not when it lists the skills (spec issue-3800 +// R-008). +func (p *Provider) SessionSkills(opts *trace.ParseOpts) ([]trace.SkillUse, []string, error) { + if opts == nil || !state.ValidSessionID(opts.SessionID) { + return nil, nil, errors.New("read Copilot skills: invalid session") + } + path, err := state.FindRawSessionFile(opts.SessionDir, opts.SessionID) + if err != nil { + return nil, nil, err + } + uses, _, err := scanSkills(path, opts.SessionID, 0, false) + return uses, nil, err +} + +// NewSkillLoads returns the folders of the skills that the session loaded +// since the last call, from the live event log. It reads only a log inside +// the Copilot session-state folder, and never fails. +func (p *Provider) NewSkillLoads(store *state.Store, input *trace.HookInput) []string { + if store == nil || input == nil || !state.ValidSessionID(input.SessionID) { + return nil + } + root := sessionStateRoot() + if rec, err := store.LoadSessionRecord(input.SessionID); err == nil && rec != nil && rec.CopilotStorageRoot != "" { + root = rec.CopilotStorageRoot + } + if root == "" { + return nil + } + path := input.TranscriptPath + if path == "" { + path = filepath.Join(root, input.SessionID, eventsFile) + } + if !filepath.IsAbs(path) { + return nil + } + resolved, err := resolveInsideRoot(path, root) + if err != nil { + return nil + } + + offsets, err := store.SkillScanOffsets(input.SessionID) + if err != nil || offsets == nil { + offsets = map[string]int64{} + } + uses, next, err := scanSkills(resolved, input.SessionID, offsets[mainLogKey], true) + if err != nil { + return nil + } + offsets[mainLogKey] = next + _ = store.SetSkillScanOffsets(input.SessionID, offsets) + + dirs := make([]string, 0, len(uses)) + for _, use := range uses { + dirs = append(dirs, use.Dir) + } + return dirs +} + +// skillInvokedData holds the fields of a skill.invoked event that Trace reads. +type skillInvokedData struct { + Name string `json:"name"` + Path string `json:"path"` + Trigger string `json:"trigger"` +} + +// scanSkills returns the skill uses of the log that end after the byte offset +// after, and the offset of the end of the last complete line. In live mode a +// last line with no newline is not read: Copilot is still writing it. +func scanSkills(path, sessionID string, after int64, live bool) ([]trace.SkillUse, int64, error) { + f, err := os.Open(path) + if err != nil { + return nil, after, err + } + defer f.Close() + info, err := f.Stat() + if err != nil || !info.Mode().IsRegular() { + return nil, after, errors.New("read Copilot skills: not a regular event log") + } + if info.Size() < after { + // The log is shorter than at the last scan: it is a new log. + after = 0 + } + + scanner := bufio.NewScanner(f) + scanner.Buffer(make([]byte, 64*1024), maxHookPayloadBytes) + if live { + scanner.Split(func(data []byte, atEOF bool) (int, []byte, error) { + if atEOF && !bytes.ContainsRune(data, '\n') { + return 0, nil, nil + } + return bufio.ScanLines(data, atEOF) + }) + } + + uses := map[string]*trace.SkillUse{} + var offset int64 + first := true + for scanner.Scan() { + line := scanner.Bytes() + offset += int64(len(line) + 1) + var e logEvent + ok := json.Unmarshal(line, &e) == nil + if first { + first = false + var data eventData + if !ok || e.Type != eventSessionStartRecord || json.Unmarshal(e.Data, &data) != nil || data.SessionID != sessionID { + return nil, after, errors.New("read Copilot skills: session ID mismatch") + } + continue + } + if !ok || e.Type != eventSkillInvoked || offset <= after { + continue + } + var data skillInvokedData + if json.Unmarshal(e.Data, &data) != nil || data.Name == "" || !filepath.IsAbs(data.Path) || filepath.Base(data.Path) != skill.DefinitionFile { + continue + } + dir := filepath.Dir(filepath.Clean(data.Path)) + if uses[dir] == nil { + uses[dir] = &trace.SkillUse{Name: data.Name, Dir: dir} + } + // The user starts a skill with a slash command. Copilot marks a skill + // that the model loaded as "agent-invoked". + byUser := strings.HasPrefix(data.Trigger, "user") + uses[dir].Record(eventTimestamp(e.Timestamp), !byUser, e.AgentID != "") + } + if err := scanner.Err(); err != nil { + return nil, after, fmt.Errorf("read Copilot skills: %w", err) + } + if first { + return nil, after, errors.New("read Copilot skills: missing session.start event") + } + return trace.SortedSkillUses(uses), offset, nil +} + +// eventTimestamp returns the time of an event in RFC3339 with whole seconds, +// in UTC, or "" when it cannot be read. +func eventTimestamp(timestamp string) string { + at, err := time.Parse(time.RFC3339Nano, timestamp) + if err != nil { + return "" + } + return at.UTC().Format(time.RFC3339) +} + +// SkillRoots returns the skill folders that Copilot reads, which tell where a +// skill came from. Copilot reads project skills in .github/skills, +// .agents/skills and .claude/skills, all under the repository. +func (p *Provider) SkillRoots(repoRoot string) skill.Roots { + userHome, _ := os.UserHomeDir() + home := copilotHomeDir() + roots := skill.Roots{Project: []string{repoRoot}} + if home != "" { + roots.Plugin = []string{filepath.Join(home, "installed-plugins")} + roots.User = append(roots.User, filepath.Join(home, "skills")) + } + if userHome != "" { + roots.User = append(roots.User, filepath.Join(userHome, ".agents", "skills")) + } + return roots +} diff --git a/app/cli/internal/trace/copilot/skills_test.go b/app/cli/internal/trace/copilot/skills_test.go new file mode 100644 index 000000000..c807ab28a --- /dev/null +++ b/app/cli/internal/trace/copilot/skills_test.go @@ -0,0 +1,181 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//nolint:goconst // Keep native event literals readable in regression fixtures. +package copilot + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const testSkillPath = "/work/repo/.github/skills/greeter/SKILL.md" + +// skillInvoked is a skill.invoked event, as Copilot CLI 1.0.109 writes it. +func skillInvoked(t *testing.T, name, path, trigger, agentID, at string) string { + t.Helper() + event := map[string]any{ + "type": eventSkillInvoked, + "id": "skill-" + name + "-" + at, + "timestamp": at, + "data": map[string]any{ + "name": name, "path": path, "trigger": trigger, "source": "project", + "content": "Write the greeting file.\n", + }, + } + if agentID != "" { + event["agentId"] = agentID + } + raw, err := json.Marshal(event) + require.NoError(t, err) + return string(raw) +} + +func sessionSkills(t *testing.T, content string) ([]trace.SkillUse, error) { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.WriteFile(state.RawSessionPath(dir, testSessionID), []byte(content), 0o600)) //nolint:gosec // temporary fixture path and a fixed session ID + uses, _, err := New().SessionSkills(&trace.ParseOpts{SessionDir: dir, SessionID: testSessionID}) + return uses, err +} + +func TestSessionSkills(t *testing.T) { + const at1, at2 = "2026-04-07T21:00:05.120Z", "2026-04-07T21:00:09Z" + // listing is the system message that lists the skills. It names the + // skill and its file, but it is not a use. + const listing = `{"type":"system.message","data":{"role":"system","content":""},"id":"sys","timestamp":"2026-04-07T21:00:01Z"}` + // failedTool is a skill tool call that found no skill: Copilot writes no + // skill.invoked event for it. + const failedTool = `{"type":"tool.execution_complete","data":{"toolCallId":"c1","success":false,"result":{"content":"Skill \"greeter\" not found"}},"id":"t","timestamp":"2026-04-07T21:00:02Z"}` + + tests := []struct { + name string + lines []string + want []trace.SkillUse + wantErr string + }{ + { + name: "model use", + lines: []string{skillInvoked(t, "greeter", testSkillPath, "agent-invoked", "", at1)}, + want: []trace.SkillUse{{Name: "greeter", Dir: filepath.Dir(testSkillPath), FirstUsedAt: "2026-04-07T21:00:05Z", ByModel: 1}}, + }, + { + name: "user use", + lines: []string{skillInvoked(t, "greeter", testSkillPath, "user-invoked", "", at1)}, + want: []trace.SkillUse{{Name: "greeter", Dir: filepath.Dir(testSkillPath), FirstUsedAt: "2026-04-07T21:00:05Z", ByUser: 1}}, + }, + { + name: "repeated and subagent uses", + lines: []string{ + skillInvoked(t, "greeter", testSkillPath, "agent-invoked", "", at2), + skillInvoked(t, "greeter", testSkillPath, "agent-invoked", "agent-1", at1), + }, + want: []trace.SkillUse{{Name: "greeter", Dir: filepath.Dir(testSkillPath), FirstUsedAt: "2026-04-07T21:00:05Z", ByModel: 2, InSubagents: 1}}, + }, + { + name: "listing and failed tool call are no use", + lines: []string{listing, failedTool}, + }, + { + name: "path that is not a skill definition", + lines: []string{ + skillInvoked(t, "greeter", "/work/repo/.github/skills/greeter/README.md", "agent-invoked", "", at1), + skillInvoked(t, "greeter", "relative/greeter/SKILL.md", "agent-invoked", "", at1), + skillInvoked(t, "", testSkillPath, "agent-invoked", "", at1), + }, + }, + { + name: "session mismatch", + lines: []string{skillInvoked(t, "greeter", testSkillPath, "agent-invoked", "", at1)}, + wantErr: "session ID mismatch", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + first := header + if tc.wantErr != "" { + first = strings.Replace(header, testSessionID, "other-session", 1) + } + uses, err := sessionSkills(t, first+"\n"+strings.Join(tc.lines, "\n")+"\n") + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + return + } + require.NoError(t, err) + if tc.want == nil { + assert.Empty(t, uses) + return + } + assert.Equal(t, tc.want, uses) + }) + } +} + +func TestNewSkillLoads(t *testing.T) { + use := skillInvoked(t, "greeter", testSkillPath, "agent-invoked", "", "2026-04-07T21:00:05Z") + other := skillInvoked(t, "other", "/work/repo/.github/skills/other/SKILL.md", "agent-invoked", "", "2026-04-07T21:00:06Z") + + root := copilotHome(t, headerLine+use+"\n") + logPath := filepath.Join(root, testSessionID, eventsFile) + store := newStore(t) + input := &trace.HookInput{SessionID: testSessionID, TranscriptPath: logPath} + p := New() + + assert.Equal(t, []string{filepath.Dir(testSkillPath)}, p.NewSkillLoads(store, input)) + assert.Empty(t, p.NewSkillLoads(store, input), "a use is returned once") + + // A line that Copilot is still writing is read at the next hook. + f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0) + require.NoError(t, err) + _, err = f.WriteString(other) + require.NoError(t, err) + assert.Empty(t, p.NewSkillLoads(store, input)) + _, err = f.WriteString("\n") + require.NoError(t, err) + require.NoError(t, f.Close()) + assert.Equal(t, []string{"/work/repo/.github/skills/other"}, p.NewSkillLoads(store, input)) + + // The computed path is used when the payload has none. + fresh := newStore(t) + assert.Equal(t, []string{filepath.Dir(testSkillPath), "/work/repo/.github/skills/other"}, + p.NewSkillLoads(fresh, &trace.HookInput{SessionID: testSessionID})) + + // A log outside the session-state folder is not read. + outside := filepath.Join(t.TempDir(), eventsFile) + require.NoError(t, os.WriteFile(outside, []byte(headerLine+use+"\n"), 0o600)) + assert.Empty(t, p.NewSkillLoads(newStore(t), &trace.HookInput{SessionID: testSessionID, TranscriptPath: outside})) + + assert.Empty(t, p.NewSkillLoads(nil, input)) + assert.Empty(t, p.NewSkillLoads(store, nil)) +} + +func TestSkillRoots(t *testing.T) { + home := t.TempDir() + t.Setenv("COPILOT_HOME", home) + t.Setenv("HOME", "/home/dev") + + roots := New().SkillRoots("/work/repo") + assert.Equal(t, []string{"/work/repo"}, roots.Project) + assert.Equal(t, []string{filepath.Join(home, "skills"), "/home/dev/.agents/skills"}, roots.User) + assert.Equal(t, []string{filepath.Join(home, "installed-plugins")}, roots.Plugin) +} diff --git a/app/cli/internal/trace/e2e/checks.go b/app/cli/internal/trace/e2e/checks.go index fd452000b..bfcbfaa81 100644 --- a/app/cli/internal/trace/e2e/checks.go +++ b/app/cli/internal/trace/e2e/checks.go @@ -425,7 +425,7 @@ func checkTicketPointer(s *Session) error { if err != nil { return err } - if evidence(s).Agent.Name == codex.Name { + if viewerTranscript(s) { return checkCodexSpecPointer(s, e.Digest) } for _, msg := range evidence(s).RawSession["main"] { @@ -457,7 +457,7 @@ func checkSkillTracked(s *Session) error { if e.Metadata == nil || e.Metadata.InvocationCount == 0 { return errors.New("the skill entry has no invocation") } - if evidence(s).Agent.Name == codex.Name { + if viewerTranscript(s) { return checkCodexSkillMaterials(s, e) } return nil diff --git a/app/cli/internal/trace/e2e/checks_codex.go b/app/cli/internal/trace/e2e/checks_codex.go index 1aae2434b..8090b8049 100644 --- a/app/cli/internal/trace/e2e/checks_codex.go +++ b/app/cli/internal/trace/e2e/checks_codex.go @@ -26,10 +26,21 @@ import ( "path/filepath" "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/codex" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pointer" "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession" ) +// viewerTranscript reports whether the provider of the session converts its +// native transcript to the viewer message shape. For these providers the +// suite checks that each pointer is in a viewer message, that no inline copy +// stays, and that a skill has its package: Codex and Copilot. +func viewerTranscript(s *Session) bool { + name := evidence(s).Agent.Name + return name == codex.Name || name == copilot.Name +} + // codexViewerPointer deliberately ignores source_event and other native // metadata. A matching digest there alone cannot make a viewer link work. func codexViewerPointer(lines []json.RawMessage, digest string) bool { @@ -84,11 +95,11 @@ func checkCodexSpecPointer(s *Session, digest string) error { } for _, raw := range evidence(s).RawSession["main"] { if inlineSource(raw, content) || inlineSource(raw, original) { - return errors.New("the Codex transcript retains an inline copy of the stored spec") + return errors.New("the transcript retains an inline copy of the stored spec") } } if !codexViewerPointer(evidence(s).RawSession["main"], digest) { - return errors.New("the Codex viewer message has no spec material pointer") + return errors.New("the viewer message has no spec material pointer") } return nil } @@ -130,13 +141,13 @@ func inlineSource(raw json.RawMessage, content []byte) bool { func checkCodexSkillMaterials(s *Session, entry aicodingsession.SpecEntry) error { definition, err := s.Stored.Material(entry.Digest) if err != nil { - return fmt.Errorf("read the Codex skill definition: %w", err) + return fmt.Errorf("read the skill definition: %w", err) } if !bytes.Contains(definition, []byte(skillName)) || !bytes.Contains(definition, []byte("farewell.txt")) { - return errors.New("the Codex skill material does not contain its definition") + return errors.New("the skill material does not contain its definition") } if entry.Metadata.PackageDigest == "" { - return errors.New("the Codex skill has no supporting-file package") + return errors.New("the skill has no supporting-file package") } data, err := s.Stored.Material(entry.Metadata.PackageDigest) if err != nil { @@ -151,7 +162,7 @@ func checkCodexSkillMaterials(s *Session, entry aicodingsession.SpecEntry) error for { header, err := archive.Next() if errors.Is(err, io.EOF) { - return errors.New("the Codex skill package has no matching definition") + return errors.New("the skill package has no matching definition") } if err != nil { return err @@ -162,7 +173,7 @@ func checkCodexSkillMaterials(s *Session, entry aicodingsession.SpecEntry) error return err } if !bytes.Equal(content, definition) { - return errors.New("the Codex skill package differs from its stored definition") + return errors.New("the skill package differs from its stored definition") } return nil } diff --git a/app/cli/internal/trace/e2e/checks_more.go b/app/cli/internal/trace/e2e/checks_more.go index 716242af3..0354f4dd6 100644 --- a/app/cli/internal/trace/e2e/checks_more.go +++ b/app/cli/internal/trace/e2e/checks_more.go @@ -30,7 +30,6 @@ import ( "time" "github.com/chainloop-dev/chainloop/app/cli/internal/trace" - "github.com/chainloop-dev/chainloop/app/cli/internal/trace/codex" tracegit "github.com/chainloop-dev/chainloop/app/cli/internal/trace/git" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pointer" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" @@ -180,18 +179,18 @@ func checkBothCommitsCredited(s *Session) error { // checkPastedImage checks that the pasted image is stored once as an image // spec entry, and that the transcript holds a pointer in place of the image. func checkPastedImage(s *Session) error { - if evidence(s).Agent.Name == codex.Name { + if viewerTranscript(s) { count := 0 for _, e := range evidence(s).Spec { if e.Kind == aicodingsession.SpecKindImage { count++ if !codexViewerPointer(evidence(s).RawSession["main"], e.Digest) { - return errors.New("the Codex viewer message has no image material pointer") + return errors.New("the viewer message has no image material pointer") } } } if count != 1 { - return fmt.Errorf("the repeated Codex paste produced %d image materials, want one", count) + return fmt.Errorf("the repeated paste produced %d image materials, want one", count) } } for _, e := range evidence(s).Spec { diff --git a/app/cli/internal/trace/e2e/checks_tokens.go b/app/cli/internal/trace/e2e/checks_tokens.go index bb73c4690..983f165f8 100644 --- a/app/cli/internal/trace/e2e/checks_tokens.go +++ b/app/cli/internal/trace/e2e/checks_tokens.go @@ -19,9 +19,11 @@ import ( "errors" "fmt" "math/big" + "strings" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/claude" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/codex" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession" ) @@ -93,6 +95,12 @@ func checkCacheTokenAccounting(s *Session) error { } } } + case copilot.Name: + var err error + want, err = copilotSourceUsage(d.RawSession["main"]) + if err != nil { + return err + } default: return fmt.Errorf("%w: cache accounting source comparison is not implemented for %s", errNotCovered, d.Agent.Name) } @@ -111,6 +119,57 @@ func checkCacheTokenAccounting(s *Session) error { return nil } +// copilotSourceUsage sums the session.usage_record events of the Copilot event +// log, one for each API call, independently of the provider parser. The +// provider stores the session.shutdown totals, which Copilot computes from the +// same calls, so the two must agree. Copilot input tokens include the cache +// reads and writes. A record that Copilot wrote again for the same call +// counts once; the latest copy wins, as in the provider. +func copilotSourceUsage(records []json.RawMessage) (aicodingsession.Usage, error) { + type usage struct { + APICallID string `json:"apiCallId"` + Input int `json:"inputTokens"` + Output int `json:"outputTokens"` + Read int `json:"cacheReadTokens"` + Write int `json:"cacheWriteTokens"` + } + calls := map[string]usage{} + for i, raw := range records { + var r struct { + ID string `json:"id"` + Type string `json:"type"` + Data struct { + Usage *usage `json:"usage"` + } `json:"data"` + } + if json.Unmarshal(raw, &r) != nil || r.Type != "session.usage_record" || r.Data.Usage == nil { + continue + } + // The stored transcript is redacted, and the redaction can replace + // each call ID with the same placeholder. Such an ID tells no calls + // apart, so the event ID is used. + key := r.Data.Usage.APICallID + if key == "" || strings.Contains(key, redactedPlaceholder) { + key = "event-" + r.ID + } + if key == "event-" { + key = fmt.Sprintf("record-%d", i) + } + calls[key] = *r.Data.Usage + } + if len(calls) == 0 { + return aicodingsession.Usage{}, errors.New("the Copilot event log has no source token usage") + } + var want aicodingsession.Usage + for _, u := range calls { + want.InputTokens += u.Input - u.Read - u.Write + want.OutputTokens += u.Output + want.CacheReadInputTokens += u.Read + want.CacheCreationInputTokens += u.Write + } + return want, nil +} + // sourceTokens keeps Codex's inclusive input until the source totals are known. type sourceTokens struct { Input int `json:"input_tokens"` diff --git a/app/cli/internal/trace/e2e/checks_tokens_test.go b/app/cli/internal/trace/e2e/checks_tokens_test.go index 1fcc893c9..b3928e6db 100644 --- a/app/cli/internal/trace/e2e/checks_tokens_test.go +++ b/app/cli/internal/trace/e2e/checks_tokens_test.go @@ -19,10 +19,12 @@ import ( "encoding/json" "errors" "os" + "strings" "testing" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/claude" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/codex" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession" "github.com/stretchr/testify/assert" @@ -221,3 +223,46 @@ func TestCacheAccountingCumulativeSources(t *testing.T) { require.NoError(t, checkCacheTokenAccounting(cacheSession(codex.Name, records...))) } } + +func TestCopilotCacheAccountingSourceComparison(t *testing.T) { + // Copilot input tokens include the cache reads and writes. Copilot can + // write the record of one API call again: the call counts once. + first := `{"type":"session.usage_record","data":{"usage":{"model":"m","apiCallId":"a","inputTokens":600,"outputTokens":20,"cacheReadTokens":500,"cacheWriteTokens":50}}}` + second := `{"type":"session.usage_record","data":{"usage":{"model":"m","apiCallId":"b","inputTokens":400,"outputTokens":30,"cacheReadTokens":300,"cacheWriteTokens":50}}}` + viewer := `{"type":"assistant","uuid":"x","message":{"role":"assistant","content":[]},"source_event":` + first + `}` + + for _, tc := range []struct { + name string + records []string + change func(*aicodingsession.Usage) + wantErr string + }{ + {name: "per-call records", records: []string{first, second}}, + {name: "repeated record", records: []string{first, second, first}}, + {name: "viewer line is not a record", records: []string{first, second, viewer}}, + { + // The redaction replaces each call ID with the same placeholder. + // The event ID then tells the records apart. + name: "redacted call IDs", + records: []string{ + strings.Replace(strings.Replace(first, `"apiCallId":"a"`, `"apiCallId":"[CHAINLOOP_TRACE_REDACTED:generic-api-key]"`, 1), `{"type"`, `{"id":"e1","type"`, 1), + strings.Replace(strings.Replace(second, `"apiCallId":"b"`, `"apiCallId":"[CHAINLOOP_TRACE_REDACTED:generic-api-key]"`, 1), `{"type"`, `{"id":"e2","type"`, 1), + }, + }, + {name: "cache counted as input", records: []string{first, second}, change: func(u *aicodingsession.Usage) { u.InputTokens = 1000; u.TotalTokens = 1050 }, wantErr: "do not match"}, + {name: "no records", wantErr: "no source token usage"}, + } { + t.Run(tc.name, func(t *testing.T) { + s := cacheSession(copilot.Name, tc.records...) + if tc.change != nil { + tc.change(s.Stored.Evidence.Data.Usage) + } + err := checkCacheTokenAccounting(s) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + return + } + require.NoError(t, err) + }) + } +} diff --git a/app/cli/internal/trace/e2e/copilot.go b/app/cli/internal/trace/e2e/copilot.go index 34d8cfd0c..ddc18501a 100644 --- a/app/cli/internal/trace/e2e/copilot.go +++ b/app/cli/internal/trace/e2e/copilot.go @@ -35,10 +35,6 @@ const copilotHooksPath = ".github/hooks/chainloop-trace.json" // copilotHooksPath. const copilotSessionStartEvent = "sessionStart" -// errCopilotImages is the error of a run with pasted images. The headless -// Copilot CLI has no input for an image. -var errCopilotImages = errors.New("copilot: the headless CLI cannot attach a pasted image") - // Copilot is the harness adapter of GitHub Copilot CLI. The Copilot agent in // VS Code reads the same hook file, but it has no headless mode, so the // suite runs the CLI only. @@ -96,10 +92,6 @@ func parseCopilotVersion(out []byte) (string, error) { // The headless output does not show the hook responses, so the hook messages // are not reported. func (c *Copilot) Run(ctx context.Context, req RunRequest) (*RunOutput, error) { - if len(req.Images) > 0 { - return nil, errCopilotImages - } - home := filepath.Join(filepath.Dir(req.Dir), "copilot-home") if err := os.MkdirAll(home, 0o700); err != nil { return nil, err @@ -116,6 +108,24 @@ func (c *Copilot) Run(ctx context.Context, req RunRequest) (*RunOutput, error) { flagModel, req.Model, } + // A pasted image goes in as an attached file, from outside the + // repository, so that the agent cannot commit it. A prompt-mode run has + // no paste: --attachment is its input for an image. + if len(req.Images) > 0 { + dir, err := os.MkdirTemp("", "chainloop-trace-e2e-") + if err != nil { + return nil, err + } + defer os.RemoveAll(dir) + for i, img := range req.Images { + path := filepath.Join(dir, fmt.Sprintf("pasted-%d.png", i+1)) + if err := os.WriteFile(path, img, 0o600); err != nil { + return nil, err + } + args = append(args, "--attachment", path) + } + } + name := c.bin() if len(req.Wrapper) > 0 { name = req.Wrapper[0]