From 461f64cc4798442fda4ea993ab3f6aadbc11ffd2 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 00:08:04 +0100 Subject: [PATCH 01/16] docs(spec): add issue-3800 GitHub Copilot support in Chainloop Trace Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- .../issue-3800-copilot-trace-provider.md | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 docs/specs/issue-3800-copilot-trace-provider.md diff --git a/docs/specs/issue-3800-copilot-trace-provider.md b/docs/specs/issue-3800-copilot-trace-provider.md new file mode 100644 index 000000000..deb5dd611 --- /dev/null +++ b/docs/specs/issue-3800-copilot-trace-provider.md @@ -0,0 +1,169 @@ +--- +owner: migmartri +ticket: https://github.com/chainloop-dev/chainloop/issues/3800 +prd: +--- + + + +# Spec issue-3800: GitHub Copilot support in Chainloop Trace + +## Summary + +Chainloop Trace supports developers who use GitHub Copilot as their coding agent. One Copilot provider covers Copilot CLI and the Copilot agent in VS Code. Both hosts run the same Copilot agent, read the same repository hook files, and keep session transcripts on disk. Developers select Copilot during initialization, or trace one command with temporary hooks. Trace records Copilot sessions as AI coding-session evidence. + +## Problem + +- Developers who use Copilot cannot attach Trace evidence to their commits. Trace supports Claude Code, Cursor, OpenCode, Pi, and Codex only. +- The Copilot agent runs hooks from `.claude/settings.json` too. In a repository with Claude Code Trace hooks, a Copilot session can start the Claude Code hooks. Trace then records the session under the wrong provider. + +## Goals and Non-Goals + +- Goal: Developers can record Copilot sessions from Copilot CLI and from VS Code, in local storage or in the control plane. +- Goal: Evidence includes conversations, models, tokens, estimated cost, tools, code attribution, used skills, and pointers for spec sources and pasted images. +- Non-goal: Support the older VS Code agent that GitHub calls the "Local" harness. It has a different hook parser and different transcript storage. Follow-up: a new ticket, if users ask for it. +- Non-goal: Trace sessions of the Copilot cloud coding agent. It runs in GitHub Actions, not on the computer of the developer, and no developer push follows it. +- Non-goal: Record subagents as separate entries in the evidence. Copilot writes no separate child transcripts. The hooks still attribute the edits of a subagent. Follow-up: a new ticket. +- Non-goal: Change the evidence schema, the control-plane APIs, or the default provider. + +## Requirements + +### R-001: One Copilot provider for both hosts + +Trace MUST offer Copilot during initialization. Initialization and the command wrapper MUST accept the Copilot provider flag. Developers MUST be able to select Copilot together with other providers. Trace MUST record a session from Copilot CLI and a session from the Copilot agent in VS Code with the same provider. Trace MUST accept each hook payload form that the Copilot agent sends. + +### R-002: Hook lifecycle + +Initialization MUST install the Copilot hooks in a hook file that Trace owns, in the repository hook folder of Copilot. A second installation MUST produce the same content. Installation MUST NOT overwrite a file that holds hooks that Trace did not write. Uninstall MUST delete only that file, and only when all its hooks are Trace hooks. Other hook files MUST stay unchanged. The command wrapper MUST omit the Trace session-end hook, and MUST restore the previous state after the command exits. + +### R-003: One record for each session + +Trace MUST record a Copilot session one time, under the Copilot provider. The Claude Code hooks MUST ignore Copilot payloads, also in a repository with no Copilot provider. They MUST NOT record a session, attribute an edit, or send a response for them. + +### R-004: Session evidence + +Trace MUST capture the session identity, timing, agent version, conversation, tool calls, models, and token usage from the Copilot session transcript. Missing or unreadable data MUST produce a warning. Token totals MUST come from the final session summary when the transcript holds it. When the summary is missing, token totals SHOULD come from the counts of each message, with a warning. Cost MUST use embedded API prices, the same rule as Claude Code and Codex, so that cost compares across providers. An unknown model MUST give a warning. + +### R-005: Code attribution + +Trace MUST attribute the edits of the Copilot file tools and shell tools. A tool hook MUST recover a session-start event that Trace did not get. + +### R-006: Private session copies + +Trace MUST parse its private copy of the session transcript. Copying MUST check the session identity, and MUST reject paths outside the Copilot session storage, symbolic-link escapes included. A failed copy MUST keep the previous copy. Local capture and parsing MUST work with no network and no login. + +### R-007: Session instructions + +Trace MUST send the spec capture instructions at session start. After a push, Trace MUST show the session link through the post-tool channel. Each hook response MUST be one JSON document at most, and an empty message MUST produce no output. + +### R-008: Skills used during the session + +Trace MUST record the skills that a Copilot session used, and capture each skill folder through the existing skill evidence pipeline. A skill listing alone MUST NOT count as a skill use. + +### R-009: Pointers for spec sources and pasted images + +Trace MUST replace exact copies of stored spec sources in the transcript with pointers to their materials. Trace MUST store each distinct pasted image one time as an image material, and replace its copies with pointers. Partial reads, changed content, failed operations, and data that Trace cannot decode MUST stay inline. + +### R-010: Verification and compatibility + +The end-to-end suite MUST have a Copilot column, run with Copilot CLI. A person MUST check a VS Code session by hand before each milestone merges. The compatibility tables MUST show the results, and MUST say which cells the VS Code check covers. + +## Constraints + +- The hook contract follows the GitHub reference for Copilot hooks at the time of the build. The VS Code hooks are in preview. +- The Copilot agent drops the output of the user-prompt hook. So Copilot gets no spec reminder at each prompt. It gets the full instruction at session start, as Cursor does. +- The Copilot hook payloads carry no tool call ID. Follows TRC-006: the file snapshot key is the session and the path. +- The Copilot agent stops a tool call when a pre-tool hook fails. The Trace hooks never fail, and always exit with success. + +## Proposal + +The developer runs Trace initialization and selects Copilot. Trace writes its own hook file into the repository hook folder of Copilot. The developer then works in Copilot CLI or in VS Code. Copilot sends session, prompt, tool, and stop events to the Trace hooks. + +Each hook detects the payload form. Copilot CLI sends camel-case fields. The VS Code form adds an event name and snake-case fields. It has one stop event for the end of a turn and for the end of a session. Trace maps both forms to the same session lifecycle. It snapshots files before the file tools, and snapshots the working tree around shell commands. + +Copilot keeps each session as a JSON Lines event log in its user folder. Trace copies the log into private storage at session boundaries and again before evidence assembly. Copilot writes the token totals after the last hook returns, so the copy at push time holds them. The parser keeps the native records, and derives the conversation, tools, models, and token usage. + +```mermaid +flowchart LR + A[trace init --copilot] --> B[Trace hook file in the Copilot hook folder] + B --> C1[Copilot CLI] + B --> C2[VS Code Copilot agent] + C1 --> D[Trace hooks: payload form detection] + C2 --> D + D --> E[Snapshots and private transcript copy] + E --> F[git push] + F --> G[Local evidence or control-plane attestation] +``` + +## Decision Record + +### D-001: One provider for Copilot CLI and VS Code + +One Copilot provider handles both hosts, with one hook file and one transcript parser. + +- Why: GitHub documents one Copilot agent for VS Code, the Copilot app, and Copilot CLI, with the same hook files and events. Another open-source trace tool uses one Copilot integration for both hosts. +- Alternatives considered: + - Two providers: two hook files that Copilot reads together, so each session fires twice. Developers must also pick a host. +- Source: drafting. + +### D-002: Trace owns a dedicated hook file + +Trace writes its own file in the Copilot hook folder. Each hook in it carries the Trace marker text, and the marker text proves ownership. This follows the Pi pattern (TRC-004), which owns its extension file. + +- Why: Copilot reads every file in the folder, so Trace needs no merge with the files of the user. A whole file is simple to install, find, and delete. +- Alternatives considered: + - Merge into a file of the user, found by marker text, as Claude Code, Cursor, and Codex do: those agents read one file only. Copilot does not need it. +- Source: drafting. + +### D-003: One spec for the Copilot provider and the Claude Code guard + +The guard that stops the Claude Code hooks on Copilot payloads (R-003) ships with the Copilot provider. + +- Why: the guard fixes a problem that exists today, but the Copilot provider cannot meet "one record for each session" without it. One review covers both sides of the same payload detection. +- Alternatives considered: + - A separate bug ticket and fix first: one more review cycle for a small change that this spec needs anyway. +- Source: drafting. + +### D-004: One spec for the core provider and the milestone-2 extensions + +Skills, spec pointers, and pasted-image pointers (R-008, R-009) are in this spec, as milestone 2. + +- Why: the parent issue groups them with the core provider for complete Copilot support, as the Codex spec did. Milestone 1 delivers the core provider first. +- Alternatives considered: + - A separate spec: it splits requirements that the parent issue groups, and repeats the provider context. +- Source: drafting, and the scope of the parent issue. + +## Open Questions + +- [ ] **Does the Copilot agent in VS Code write the same session event log as Copilot CLI?** Proposed: yes. GitHub says that the hosts share the agent and its hooks. Milestone 1 checks this. If the log is different, VS Code sessions keep their hooks and attribution. Trace then gives a warning about the transcript, and a follow-up ticket adds a parser. This fallback supersedes the VS Code part of R-004 and changes the first goal. + +## Milestones + +1. **Core Copilot provider.** R-001 to R-007, and R-010 for these requirements. Selection, hooks, payload forms, the Claude Code guard, session evidence, attribution, local storage, control-plane uploads, and session messages. +2. **Copilot skills, spec pointers, and pasted images.** R-008, R-009, and R-010 for these requirements, through the shared evidence pipeline. + +## Risks + +| Risk | Mitigation | +|------|------------| +| Copilot changes its hook payloads or its event log. The VS Code hooks are in preview. | Accept both payload forms, keep unknown records, give a warning for unreadable records, and test with sanitized fixtures. | +| Developers commit the hook file. Teammates without the Chainloop CLI, and the cloud coding agent, also run the hooks. | The existing hook command guard exits with success when the CLI is not installed. | +| The estimated cost differs from the Copilot bill. | The compatibility tables say that cost is an API-price estimate. | +| The token totals are missing when the agent stops before it writes its session summary. | Use the token counts of each message, and give a warning. | From d5fe4401f9a59ddaca108a7269d1b45d423e7498 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 00:11:38 +0100 Subject: [PATCH 02/16] docs(spec): drop scope-only decisions from issue-3800 spec Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- .../specs/issue-3800-copilot-trace-provider.md | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/docs/specs/issue-3800-copilot-trace-provider.md b/docs/specs/issue-3800-copilot-trace-provider.md index deb5dd611..ee3bea54b 100644 --- a/docs/specs/issue-3800-copilot-trace-provider.md +++ b/docs/specs/issue-3800-copilot-trace-provider.md @@ -132,24 +132,6 @@ Trace writes its own file in the Copilot hook folder. Each hook in it carries th - Merge into a file of the user, found by marker text, as Claude Code, Cursor, and Codex do: those agents read one file only. Copilot does not need it. - Source: drafting. -### D-003: One spec for the Copilot provider and the Claude Code guard - -The guard that stops the Claude Code hooks on Copilot payloads (R-003) ships with the Copilot provider. - -- Why: the guard fixes a problem that exists today, but the Copilot provider cannot meet "one record for each session" without it. One review covers both sides of the same payload detection. -- Alternatives considered: - - A separate bug ticket and fix first: one more review cycle for a small change that this spec needs anyway. -- Source: drafting. - -### D-004: One spec for the core provider and the milestone-2 extensions - -Skills, spec pointers, and pasted-image pointers (R-008, R-009) are in this spec, as milestone 2. - -- Why: the parent issue groups them with the core provider for complete Copilot support, as the Codex spec did. Milestone 1 delivers the core provider first. -- Alternatives considered: - - A separate spec: it splits requirements that the parent issue groups, and repeats the provider context. -- Source: drafting, and the scope of the parent issue. - ## Open Questions - [ ] **Does the Copilot agent in VS Code write the same session event log as Copilot CLI?** Proposed: yes. GitHub says that the hosts share the agent and its hooks. Milestone 1 checks this. If the log is different, VS Code sessions keep their hooks and attribution. Trace then gives a warning about the transcript, and a follow-up ticket adds a parser. This fallback supersedes the VS Code part of R-004 and changes the first goal. From 669dd15d6b67cf00b7a802e445a052d909c5fafa Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 00:17:02 +0100 Subject: [PATCH 03/16] docs(plan): add issue-3800 GitHub Copilot Trace provider plan Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- .../issue-3800-copilot-trace-provider.md | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 docs/plans/issue-3800-copilot-trace-provider.md diff --git a/docs/plans/issue-3800-copilot-trace-provider.md b/docs/plans/issue-3800-copilot-trace-provider.md new file mode 100644 index 000000000..9f494d706 --- /dev/null +++ b/docs/plans/issue-3800-copilot-trace-provider.md @@ -0,0 +1,169 @@ +--- +owner: migmartri +ticket: https://github.com/chainloop-dev/chainloop/issues/3800 +spec: docs/specs/issue-3800-copilot-trace-provider.md +--- + + + +# Plan issue-3800: GitHub Copilot support in Chainloop Trace + +## Overview + +Add a Copilot provider to Chainloop Trace, built like the Codex provider. It installs one hook file that Trace owns in the Copilot hook folder, as the Pi provider owns its extension file. The shared agent and git hook handlers stay as they are. The provider gives only the Copilot parts: hook input, transcript copy, transcript parser, and price table. The Claude Code provider gets a guard for Copilot payloads, like its existing guard for Cursor payloads. Milestone 2 adds skills, spec pointers, and pasted images with the Codex extension pattern. + +## Architecture and impact + +```mermaid +flowchart LR + A[Copilot CLI or VS Code Copilot agent] --> B[Copilot hook file, new] + A -. also runs .-> C[Claude Code hook settings, read only] + B --> D[Trace hook commands, changed] + C --> E[Claude Code provider, changed] + D --> F[Copilot provider, new] + F --> G[Shared agent and git hook handlers, read only] + F --> H[Copilot session event log, read only] + G --> I[Trace state and evidence pipeline, read only] + J[trace init and trace run, changed] --> F + K[End-to-end suite, changed] --> A +``` + +- Copilot provider: hook install and uninstall, hook input for both payload forms, transcript copy and parse, cost, announcements, and in M2 the three extensions. +- Copilot hook file: the hook entries that Copilot CLI and VS Code read. Trace owns the whole file. +- Trace hook commands: the `copilot` hook subcommands that the hook file calls. +- Claude Code provider: ignores a Copilot payload, so a Copilot session gives one record. +- trace init and trace run: the Copilot flag, the wizard choice, and the trust note. +- End-to-end suite: a Copilot column that runs Copilot CLI. + +| Impact on | What changes | +|-----------|--------------| +| Users and other parts of the product | New Copilot choice in `trace init` and `trace run`. Repositories with Claude Code hooks stop recording Copilot sessions as Claude Code sessions. | +| Data and migrations | None. New provider name `copilot` in session records and evidence. The evidence schema does not change. | +| Configuration and deployment | New repository file in the Copilot hook folder, written by `trace init`. No server change. | +| Compatibility | Other providers do not change. The Claude Code guard skips only payloads that Claude Code never sends. | +| Rollback | Revert the PR. Users remove the Copilot hook file with `trace uninstall` or by hand. | + +## Milestones + +| # | Milestone | Requirements | Depends on | +|---|-----------|--------------|------------| +| M1 | Core Copilot provider | R-001, R-002, R-003, R-004, R-005, R-006, R-007, R-010 | none | +| M2 | Copilot skills, spec pointers, and pasted images | R-008, R-009, R-010 | M1 | + +### M1: Core Copilot provider + +Developers select Copilot in `trace init` or `trace run`, and Trace records their Copilot CLI and VS Code sessions as evidence, with attribution and estimated cost. The milestone adds the provider, its hook commands and flags, the Claude Code guard, the end-to-end column, and the compatibility tables. It follows the Codex provider for transcript copy, parse, and pricing, and the Pi provider for file ownership. + +**Done when:** after a push, a Copilot CLI session in a test repository gives evidence with conversation, models, tokens, cost, tools, and attributed lines. A Claude Code hook gives no record for the same session. Checked by the provider unit tests, the Claude Code test for a Copilot payload, and the end-to-end suite for the Copilot column. A person also checks one VS Code session in a repository with `trace init --copilot --claude`. + +
+Technical details + +Changes: + +**Copilot provider** + +- `app/cli/internal/trace/copilot/provider.go`: `Name = "copilot"`, `var _ trace.Provider = (*Provider)(nil)`. Snapshot attribution strategy, as Codex. `SupportsSessionStartBanner` true, `SupportsSessionStartInstruction` true, `SupportsPromptReminder` false (spec Constraints). `AnnounceToUser` writes `additionalContext` in the post-tool response (R-007). +- `app/cli/internal/trace/copilot/hooks.go`: `InstallHooks`, `InstallHooksForTraceRun` (no `sessionEnd`), `UninstallHooks`, `HooksInstalled`, `SettingsFile` for `.github/hooks/chainloop-trace.json`. Format `{"version": 1, "hooks": {: [{"type": "command", "bash": ...}]}}`. Events: `sessionStart`, `preToolUse`, `postToolUse`, `sessionEnd`. No `agentStop`: it fires at each turn, and no provider hooks a turn end (see the `session.idle` note in `opencode/hooks.go`). Each `bash` command is wrapped with `trace.GuardHookCommand`, so the hook exits with success when the CLI is not installed. Ownership as in `pi/hooks.go` (`allowUnowned` for `trace run`), but the proof is the marker `chainloop trace hook copilot` in every entry, matched through the guard wrapper as in `codex/hooks.go`: install refuses a file with an entry without the marker, except for `trace run`. Uninstall deletes the file only when every entry has the marker (R-002, D-002). +- `app/cli/internal/trace/copilot/hooks.go`: `ReadHookInput` decodes a typed struct that accepts camelCase and snake_case keys (`sessionId`/`session_id`, `transcriptPath`/`transcript_path`, `toolName`/`tool_name`, `toolArgs`/`tool_input`), with the size limit of the other providers. In the camelCase form `toolArgs` is a JSON string, so a second typed decode reads it. File tools `create` and `edit` set `FilePath`. Shell tools `bash` and `powershell` set `Command`. When the payload has no transcript path, `ReadHookInput` uses `~/.copilot/session-state//events.jsonl`, or the same path under `$COPILOT_HOME`. No `ToolUseID`: follows TRC-006. +- `app/cli/internal/trace/copilot/copy.go`: `CopySessionData` copies `events.jsonl` into the session folder. It checks the session ID, rejects paths outside the Copilot session-state folder after it resolves symbolic links, and keeps the previous copy on failure (R-006). It reads the session-state root from the session record, so the push-time copy works when `$COPILOT_HOME` differs at push. +- `app/cli/internal/trace/state/session.go`: a `CopilotStorageRoot` field in `SessionRecord`, set at the first hook, as `CodexStorageRoot` (R-004, R-006). +- `app/cli/internal/trace/copilot/transcript.go`, `parse.go`: `ParseSession` reads only the copy. It maps `session.start`, `user.message`, `assistant.message` (with `toolRequests`), `tool.execution_complete`, `assistant.turn_*`, and `session.shutdown`. Token totals come from `session.shutdown.modelMetrics`. Without it, per-message `outputTokens` and a warning (R-004). Unknown record types stay in `RawSession["main"]`. +- `app/cli/internal/trace/copilot/pricing.go`, `pricing.json`: embedded table and `estimateCost`, copied from the Codex pattern, with the models that Copilot offers. Unknown model: default price and a warning. + +**Claude Code provider** + +- `app/cli/internal/trace/claude/hooks.go`: in `ReadHookInput`, return an empty `HookInput` for a Copilot payload, next to the `cursor_version` guard (R-003). The field that identifies a Copilot payload is an open question. + +**CLI wiring** + +- `app/cli/internal/trace/providers/registry.go`: register `copilot.New()`. +- `app/cli/cmd/trace_init_providers.go`, `trace_init.go`, `trace_run.go`: `copilot` field in `traceProviderFlags`, `any()`, `names()`, the `--copilot` flag, the wizard choice, and a one-line Copilot note in `writeTraceHarnessNotes` that names the hook file. +- `app/cli/cmd/trace_hook.go`: `newTraceHookCopilotCmd` with `session-start`, `pre-tool-use`, `post-tool-use`, and `session-end`, with `skipActionOptsInit`. +- `make generate` for the CLI reference. +- License header year in each changed file. + +**End-to-end suite and documentation** + +- `app/cli/internal/trace/e2e/copilot.go`: `e2e.Harness` that runs `copilot -p ... --allow-all-tools` in the test repository. Add it to the `harnesses` map in `e2e_test.go`, and a version and models entry in `config.yaml`. +- `app/cli/internal/trace/README.md`: provider list, a Copilot column in each table, "Why not Yes" lines (no prompt reminder, no subagents, no tool call ID, cost is an API-price estimate), a row in "How each agent is hooked in", and which cells the manual VS Code check covers. + +Interfaces that later milestones use: + +- `copilot.Name`: `"copilot"`, the provider name in session records and evidence. +- The transcript record types of `transcript.go`: M2 reads them to find skill loads, file reads, and pasted images. + +Tests: + +- `TestInstallHooks*`: each command has the missing-CLI guard, same content on a second run, refusal on a user file, `trace run` file without `sessionEnd`, uninstall keeps other hook files. +- `TestReadHookInput*`: camelCase and snake_case payloads, file tools, shell tools, computed transcript path. +- `TestCopySessionData*`: wrong session ID, path outside session-state, symbolic-link escape, failed copy keeps the previous copy, push with a different `$COPILOT_HOME` uses the stored root. +- `TestParseSession*`: sanitized `testdata/` log with and without `session.shutdown`, unknown records kept, warnings. +- `TestEstimateCost*`: known model, unknown model warning. +- `claude` `TestReadHookInput_CopilotPayload`: a Copilot payload gives an empty input. +- `providers/capabilities_test.go`, `cmd/trace_init_providers_test.go`, `cmd/trace_init_test.go`: updated for the new provider. + +Verify: `make -C app/cli lint test`, then `CHAINLOOP_E2E_HARNESS="Copilot" make -C app/cli test-trace-e2e`, then one VS Code Copilot session in a test repository with `trace init --copilot --claude`. + +
+ +### M2: Copilot skills, spec pointers, and pasted images + +Copilot evidence gets the used skills, and pointers in place of copies of spec sources and pasted images. The provider adds the three optional extensions on its transcript format. It follows the Codex extensions and the shared skill and pointer pipeline. + +**Done when:** a Copilot session loads a skill, reads a captured spec file, and gets a pasted image. Its evidence has a skill entry, pointers in the transcript, and one image material. Checked by the provider unit tests, the end-to-end skill, spec, and image checks for the Copilot column, and one VS Code session checked by hand. + +
+Technical details + +Changes: + +- `app/cli/internal/trace/copilot/skills.go`: `SkillTracker` with `SkillRoots` for the Copilot skill folders. It finds skill loads in the transcript only, not in a skill listing (R-008). +- `app/cli/internal/trace/copilot/materials.go`: `SpecCopyReplacer` and `PastedImageFinder` on `user.message` attachments, `assistant.message` tool requests, and `tool.execution_complete` results. It uses the shared `pointer` package. Partial reads, changed content, failed tools, and data that cannot be decoded stay inline (R-009). +- `app/cli/internal/trace/copilot/provider.go`: compile-time checks for the three extensions. +- `app/cli/internal/trace/e2e/`: Copilot checks for skills, spec pointers, and images, as `checks_codex.go`. +- `app/cli/internal/trace/README.md`: Copilot cells for skills, spec pointers, and pasted images. + +Tests: + +- `TestSkillTracker*`: a skill load counts, a listing does not. +- `TestSpecCopyReplacer*`: an exact copy becomes a pointer; a partial read, changed content, and a failed tool stay inline. +- `TestPastedImageFinder*`: two copies of one image give one material; an image from a tool result does not count; data that cannot be decoded stays inline. + +Verify: `make -C app/cli lint test`, then `CHAINLOOP_E2E_HARNESS="Copilot" make -C app/cli test-trace-e2e`, then one VS Code session with a skill and a pasted image. + +
+ +## Open Questions + +- [ ] **What do the real Copilot hooks send and show, in Copilot CLI and in VS Code?** This question has four parts. Which field tells the Claude Code provider that Copilot sent a payload? Which tool names and key forms does VS Code send? Does VS Code send `sessionEnd`? Does Copilot show the session-start and post-tool output? Proposed: at the start of M1, capture real payloads from both hosts, also through `.claude/settings.json`. For the guard, pick a field that Claude Code never sends, for example `timestamp` or a transcript path under the Copilot session-state folder. Set the `Supports*` values and the tool lists from the captures. With no post-tool channel, `AnnounceToUser` returns `ErrAnnounceUnsupported`. If VS Code sends no `sessionEnd`, stop and take the lifecycle choice to the spec. +- [ ] **Does the VS Code Copilot agent write the same event log as Copilot CLI?** This is the open question of the spec. Proposed: check it with the manual VS Code session of M1 before the parser is final. +- [ ] **Which Copilot CLI version does the end-to-end suite pin?** Proposed: the latest release at the start of M1, in `config.yaml`. + +## Skipped and risks + +| Skipped step | Reason | Follow-up | +|--------------|--------|-----------| +| Shared price table package for Claude Code, Codex, and Copilot | No requirement asks for it. Copy the Codex pattern. | none | +| Prompt-submit hook | Copilot drops its output (spec Constraints). | none | +| Subagent evidence | Spec Non-Goal. | new ticket | +| VS Code Local agent | Spec Non-Goal. | new ticket | +| End-to-end driver for VS Code | VS Code has no headless mode. R-010 asks for a manual check. | none | + +Not checked: the exact Copilot payloads and the VS Code event log on a real machine. Copilot is not installed here. Also not checked: the skill folders that Copilot reads. + +| Risk | Mitigation | +|------|------------| +| A Copilot payload has a field shape that the research did not show. | Capture real payloads first in M1, and keep them as sanitized test data. | +| A pre-tool hook error stops the Copilot tool call. | The handlers already return success on every error. A unit test runs the pre-tool hook with bad input. | +| `session.shutdown` is not in the copy at push time. | Copy again at push time, and use per-message tokens with a warning. | From 35dd51be217194f30bd9720b1d4935e3dfb2e876 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 01:08:20 +0100 Subject: [PATCH 04/16] feat(trace): add GitHub Copilot provider Add a copilot Trace provider that covers Copilot CLI and the Copilot agent in VS Code through a hook file that Trace owns in .github/hooks. It records the Copilot session event log as evidence, with attribution and an API-price cost estimate. The Claude Code provider now ignores Copilot payloads, so a Copilot session is recorded once. Implements M1 of docs/plans/issue-3800-copilot-trace-provider.md (R-001 to R-007, R-010). Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/cmd/trace_hook.go | 21 + app/cli/cmd/trace_init.go | 9 +- app/cli/cmd/trace_init_providers.go | 10 +- app/cli/cmd/trace_init_providers_test.go | 15 +- app/cli/cmd/trace_init_test.go | 10 +- app/cli/cmd/trace_run.go | 4 +- app/cli/documentation/cli-reference.md | 4 +- app/cli/internal/trace/README.md | 124 +++-- app/cli/internal/trace/claude/hooks.go | 36 ++ app/cli/internal/trace/claude/hooks_test.go | 49 ++ app/cli/internal/trace/copilot/copy.go | 193 +++++++ app/cli/internal/trace/copilot/hooks.go | 371 ++++++++++++++ app/cli/internal/trace/copilot/hooks_test.go | 258 ++++++++++ app/cli/internal/trace/copilot/parse.go | 474 ++++++++++++++++++ app/cli/internal/trace/copilot/parse_test.go | 237 +++++++++ app/cli/internal/trace/copilot/pricing.go | 77 +++ app/cli/internal/trace/copilot/pricing.json | 229 +++++++++ app/cli/internal/trace/copilot/provider.go | 149 ++++++ .../internal/trace/copilot/provider_test.go | 208 ++++++++ .../trace/copilot/testdata/session.jsonl | 13 + app/cli/internal/trace/e2e/config.yaml | 8 + app/cli/internal/trace/e2e/copilot.go | 188 +++++++ app/cli/internal/trace/e2e/copilot_test.go | 83 +++ app/cli/internal/trace/e2e/e2e_test.go | 1 + .../trace/providers/capabilities_test.go | 4 +- app/cli/internal/trace/providers/registry.go | 2 + app/cli/internal/trace/state/session.go | 4 + 27 files changed, 2717 insertions(+), 64 deletions(-) create mode 100644 app/cli/internal/trace/copilot/copy.go create mode 100644 app/cli/internal/trace/copilot/hooks.go create mode 100644 app/cli/internal/trace/copilot/hooks_test.go create mode 100644 app/cli/internal/trace/copilot/parse.go create mode 100644 app/cli/internal/trace/copilot/parse_test.go create mode 100644 app/cli/internal/trace/copilot/pricing.go create mode 100644 app/cli/internal/trace/copilot/pricing.json create mode 100644 app/cli/internal/trace/copilot/provider.go create mode 100644 app/cli/internal/trace/copilot/provider_test.go create mode 100644 app/cli/internal/trace/copilot/testdata/session.jsonl create mode 100644 app/cli/internal/trace/e2e/copilot.go create mode 100644 app/cli/internal/trace/e2e/copilot_test.go diff --git a/app/cli/cmd/trace_hook.go b/app/cli/cmd/trace_hook.go index f2eb3243e..7deba0875 100644 --- a/app/cli/cmd/trace_hook.go +++ b/app/cli/cmd/trace_hook.go @@ -22,6 +22,7 @@ import ( "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/config" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/cursor" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/opencode" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" @@ -43,6 +44,7 @@ func newTraceHookCmd() *cobra.Command { newTraceHookCursorCmd(), newTraceHookOpenCodeCmd(), newTraceHookCodexCmd(), + newTraceHookCopilotCmd(), newTraceHookPiCmd(), ) @@ -474,6 +476,25 @@ func newTraceHookCodexCmd() *cobra.Command { return cmd } +// newTraceHookCopilotCmd handles the hooks of the GitHub Copilot hook file. +// There is no user-prompt-submit hook, because Copilot drops its output. +func newTraceHookCopilotCmd() *cobra.Command { + cmd := &cobra.Command{Use: "copilot", Short: "Handle GitHub Copilot hook invocations"} + handlers := []struct { + name, description string + run func(*cobra.Command, []string) error + }{ + {"session-start", "Capture the Copilot session", func(cmd *cobra.Command, _ []string) error { return runAgentSessionStart(cmd, copilot.New()) }}, + {"pre-tool-use", "Snapshot files before a Copilot tool", func(_ *cobra.Command, _ []string) error { return action.HandleAgentPreToolUse(copilot.New(), logger) }}, + {"post-tool-use", "Record changes after a Copilot tool", func(_ *cobra.Command, _ []string) error { return action.HandleAgentPostToolUse(copilot.New(), logger) }}, + {"session-end", "Copy the completed Copilot session", func(_ *cobra.Command, _ []string) error { return action.HandleAgentSessionEnd(copilot.New(), logger) }}, + } + for _, h := range handlers { + cmd.AddCommand(&cobra.Command{Use: h.name, Short: h.description, Args: cobra.NoArgs, Annotations: map[string]string{skipActionOptsInit: trueString}, RunE: func(cmd *cobra.Command, args []string) error { InitHookLogger(); return h.run(cmd, args) }}) + } + return cmd +} + func newTraceHookPiCmd() *cobra.Command { cmd := &cobra.Command{ Use: "pi", diff --git a/app/cli/cmd/trace_init.go b/app/cli/cmd/trace_init.go index 978f64ad1..2df535303 100644 --- a/app/cli/cmd/trace_init.go +++ b/app/cli/cmd/trace_init.go @@ -29,6 +29,7 @@ import ( "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/config" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" tracegit "github.com/chainloop-dev/chainloop/app/cli/internal/trace/git" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/hooks" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" @@ -51,6 +52,7 @@ func newTraceInitCmd() *cobra.Command { opencodeFlag bool piFlag bool codexFlag bool + copilotFlag bool ) cmd := &cobra.Command{ @@ -76,7 +78,7 @@ named freely; the name is normalized to the lowercase, dash-separated form Chainloop stores. It then asks which harnesses to trace, with the ones the repository is already set up for ticked, or Claude Code on a first run; use space to tick more. Passing --org, --project or a harness flag -(--claude, --cursor, --opencode, --pi, --codex) skips the matching question. +(--claude, --cursor, --opencode, --pi, --codex, --copilot) skips the matching question. Nothing is asked in CI or when the output is redirected: there --project is required unless .chainloop.yml carries projectName. Set CHAINLOOP_NO_PROMPT to @@ -159,7 +161,7 @@ cannot use them with --local. You can use --require-trace with --local.`, // so every question is answered up front and an abort leaves the // repository untouched. selected, err := resolveTraceProviders(newNamingPrompter(os.LookupEnv), - traceProviderFlags{claude: claudeFlag, cursor: cursorFlag, opencode: opencodeFlag, pi: piFlag, codex: codexFlag}, + traceProviderFlags{claude: claudeFlag, cursor: cursorFlag, opencode: opencodeFlag, pi: piFlag, codex: codexFlag, copilot: copilotFlag}, traceInitCanPrompt(), func() []string { return configuredTraceProviders(repoRoot) }) if err != nil { return stopIfAborted(err) @@ -299,6 +301,7 @@ cannot use them with --local. You can use --require-trace with --local.`, cmd.Flags().BoolVar(&cursorFlag, "cursor", false, "install Cursor hooks") cmd.Flags().BoolVar(&piFlag, "pi", false, "install Pi extension") cmd.Flags().BoolVar(&codexFlag, "codex", false, "install Codex hooks") + cmd.Flags().BoolVar(&copilotFlag, "copilot", false, "install GitHub Copilot hooks (Copilot CLI and VS Code)") cmd.Flags().BoolVar(&opencodeFlag, "opencode", false, "install opencode hooks") return cmd @@ -394,6 +397,8 @@ func writeTraceHarnessNotes(w io.Writer, installed []trace.Provider) { switch p.Name() { case codex.Name: fmt.Fprintln(w, "For Codex, review and trust the installed hooks in Codex before starting work.") + case copilot.Name: + fmt.Fprintln(w, "For Copilot, the hooks are in .github/hooks/chainloop-trace.json. Copilot CLI and the Copilot agent in VS Code both read it.") case pi.Name: fmt.Fprintln(w, "For Pi, review the project extension at .pi/extensions/chainloop-trace.ts before starting work. Interactive Pi asks to trust project files. Non-interactive runs need saved trust or --approve.") } diff --git a/app/cli/cmd/trace_init_providers.go b/app/cli/cmd/trace_init_providers.go index 606fde834..a1bb6cca4 100644 --- a/app/cli/cmd/trace_init_providers.go +++ b/app/cli/cmd/trace_init_providers.go @@ -21,6 +21,7 @@ import ( "github.com/chainloop-dev/chainloop/app/cli/internal/trace" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/claude" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/codex" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/cursor" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/opencode" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" @@ -31,18 +32,18 @@ const providersPromptTitle = "Harnesses to trace in this repository" // traceProviderFlags records the harness flags that the user set. type traceProviderFlags struct { - claude, cursor, opencode, pi, codex bool + claude, cursor, opencode, pi, codex, copilot bool } // any reports whether the user named at least one provider. func (f traceProviderFlags) any() bool { - return f.claude || f.cursor || f.opencode || f.pi || f.codex + return f.claude || f.cursor || f.opencode || f.pi || f.codex || f.copilot } // names returns the providers the flags select, in the registry's order rather // than the order the flags happen to appear in. func (f traceProviderFlags) names() []string { - out := make([]string, 0, 4) + out := make([]string, 0, 6) if f.claude { out = append(out, claude.Name) } @@ -58,6 +59,9 @@ func (f traceProviderFlags) names() []string { if f.codex { out = append(out, codex.Name) } + if f.copilot { + out = append(out, copilot.Name) + } return out } diff --git a/app/cli/cmd/trace_init_providers_test.go b/app/cli/cmd/trace_init_providers_test.go index 3196a2ceb..ccc40b737 100644 --- a/app/cli/cmd/trace_init_providers_test.go +++ b/app/cli/cmd/trace_init_providers_test.go @@ -20,6 +20,7 @@ import ( "path/filepath" "testing" + "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/app/cli/internal/trace/providers" @@ -208,10 +209,20 @@ func TestTraceProviderFlags(t *testing.T) { }) t.Run("names follow the registry order, not the flag order", func(t *testing.T) { - f := traceProviderFlags{codex: true, pi: true, claude: true} + f := traceProviderFlags{copilot: true, codex: true, pi: true, claude: true} assert.True(t, f.any()) - assert.Equal(t, []string{providerClaudeCode, pi.Name, "codex"}, f.names()) + assert.Equal(t, []string{providerClaudeCode, pi.Name, "codex", copilot.Name}, f.names()) }) + t.Run("copilot flag", func(t *testing.T) { + f := traceProviderFlags{copilot: true} + assert.True(t, f.any()) + assert.Equal(t, []string{copilot.Name}, f.namesOrDefault()) + }) +} + +func TestTraceCommandsExposeCopilotFlag(t *testing.T) { + assert.NotNil(t, newTraceInitCmd().Flags().Lookup(copilot.Name)) + assert.NotNil(t, newTraceRunCmd().Flags().Lookup(copilot.Name)) } func TestTraceCommandsExposePiFlag(t *testing.T) { diff --git a/app/cli/cmd/trace_init_test.go b/app/cli/cmd/trace_init_test.go index ad9674398..3632b8f7d 100644 --- a/app/cli/cmd/trace_init_test.go +++ b/app/cli/cmd/trace_init_test.go @@ -22,6 +22,7 @@ import ( "slices" "testing" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/opencode" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/providers" @@ -328,15 +329,15 @@ func TestWriteTraceNextSteps(t *testing.T) { }, { name: "every harness", - providers: []string{providerClaudeCode, "cursor", opencode.Name, pi.Name, "codex"}, + providers: []string{providerClaudeCode, "cursor", opencode.Name, pi.Name, "codex", copilot.Name}, // Named in full: ".opencode" alone would pass on any file under that // directory, so it would not catch the plugin being renamed. wantFiles: []string{ chainloopYMLName, claudeSettings, ".cursor/hooks.json", ".opencode/plugins/chainloop-trace.ts", ".pi/extensions/chainloop-trace.ts", - ".codex/hooks.json", + ".codex/hooks.json", ".github/hooks/chainloop-trace.json", }, - wantHarnesses: "claude-code, cursor, opencode, pi or codex", + wantHarnesses: "claude-code, cursor, opencode, pi, codex or copilot", }, } @@ -356,6 +357,9 @@ func TestWriteTraceNextSteps(t *testing.T) { if slices.Contains(tc.providers, pi.Name) { assert.Contains(t, got, "--approve") } + if slices.Contains(tc.providers, copilot.Name) { + assert.Contains(t, got, "For Copilot") + } }) } } diff --git a/app/cli/cmd/trace_run.go b/app/cli/cmd/trace_run.go index c1e3de331..a60275ce4 100644 --- a/app/cli/cmd/trace_run.go +++ b/app/cli/cmd/trace_run.go @@ -66,6 +66,7 @@ func newTraceRunCmd() *cobra.Command { opencodeFlag bool piFlag bool codexFlag bool + copilotFlag bool ) cmd := &cobra.Command{ @@ -167,7 +168,7 @@ func newTraceRunCmd() *cobra.Command { return action.TraceRun(cmd.Context(), logger, action.TraceRunOpts{ Store: store, RepoRoot: repoRoot, - Providers: traceProviderFlags{claude: claudeFlag, cursor: cursorFlag, opencode: opencodeFlag, pi: piFlag, codex: codexFlag}.namesOrDefault(), + Providers: traceProviderFlags{claude: claudeFlag, cursor: cursorFlag, opencode: opencodeFlag, pi: piFlag, codex: codexFlag, copilot: copilotFlag}.namesOrDefault(), Command: args, ProjectName: projectFlag, Organization: organization, @@ -191,6 +192,7 @@ func newTraceRunCmd() *cobra.Command { cmd.Flags().BoolVar(&cursorFlag, "cursor", false, "install Cursor hooks") cmd.Flags().BoolVar(&piFlag, "pi", false, "install Pi extension") cmd.Flags().BoolVar(&codexFlag, "codex", false, "install Codex hooks") + cmd.Flags().BoolVar(&copilotFlag, "copilot", false, "install GitHub Copilot hooks (Copilot CLI and VS Code)") cmd.Flags().BoolVar(&opencodeFlag, "opencode", false, "install opencode hooks") // project and workflow are not required in local mode, so the check is done diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index a28098b33..01ec5e823 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -3154,7 +3154,7 @@ named freely; the name is normalized to the lowercase, dash-separated form Chainloop stores. It then asks which harnesses to trace, with the ones the repository is already set up for ticked, or Claude Code on a first run; use space to tick more. Passing --org, --project or a harness flag -(--claude, --cursor, --opencode, --pi, --codex) skips the matching question. +(--claude, --cursor, --opencode, --pi, --codex, --copilot) skips the matching question. Nothing is asked in CI or when the output is redirected: there --project is required unless .chainloop.yml carries projectName. Set CHAINLOOP_NO_PROMPT to @@ -3187,6 +3187,7 @@ Options --claude[=true|false] install Claude Code hooks (default when no harness flag is set) --codex[=true|false] install Codex hooks --contract string workflow contract to attach when creating the workflow; it must already exist and be usable by the project (default: "chainloop-ai-coding-session" when the organization has it, an empty contract otherwise) +--copilot[=true|false] install GitHub Copilot hooks (Copilot CLI and VS Code) --cursor[=true|false] install Cursor hooks -h, --help[=true|false] help for init --local[=true|false] set up local mode, with no control plane, login or workflow. The pre-push hook writes the session evidence to disk @@ -3257,6 +3258,7 @@ Options --claude[=true|false] install Claude Code hooks (default when no provider flag is set) --codex[=true|false] install Codex hooks --contract string workflow contract to attach when creating the workflow; it must already exist and be usable by the project (default: "chainloop-ai-coding-session" when the organization has it, an empty contract otherwise) +--copilot[=true|false] install GitHub Copilot hooks (Copilot CLI and VS Code) --cursor[=true|false] install Cursor hooks -h, --help[=true|false] help for run --local[=true|false] store the session on disk, with no control plane, login or workflow diff --git a/app/cli/internal/trace/README.md b/app/cli/internal/trace/README.md index 29d444090..4e1c9945c 100644 --- a/app/cli/internal/trace/README.md +++ b/app/cli/internal/trace/README.md @@ -1,6 +1,6 @@ # Chainloop Trace: agent support -Chainloop Trace records the sessions of AI coding agents as `CHAINLOOP_AI_CODING_SESSION` evidence. Each agent is a provider in this package: `claude/`, `cursor/`, `opencode/`, `pi/` and `codex/`. The interfaces are in `provider.go`, and the registry is in `providers/`. To add a provider, follow [PROVIDERS.md](PROVIDERS.md). One provider covers OpenCode 1.x and OpenCode 2: it detects the version at runtime. +Chainloop Trace records the sessions of AI coding agents as `CHAINLOOP_AI_CODING_SESSION` evidence. Each agent is a provider in this package: `claude/`, `cursor/`, `opencode/`, `pi/`, `codex/` and `copilot/`. The interfaces are in `provider.go`, and the registry is in `providers/`. To add a provider, follow [PROVIDERS.md](PROVIDERS.md). One provider covers OpenCode 1.x and OpenCode 2: it detects the version at runtime. This page lists the features of Trace, by area, and tells which agents support each one. **Keep it current.** When you add or change a provider, or add or change a feature of Trace, update this page in the same pull request. @@ -28,33 +28,40 @@ 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 …`. 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). + +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. + +The Copilot column starts at **Unknown**: the provider has unit tests, but the end-to-end suite has not run for it yet. The cells marked **No** are features that the provider does not implement. + ## Setup How Trace is added to a repository and to an agent. -| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | -|---------|---------------|-------------|--------|--------------|------------|---|---| -| Hook installation and deletion | `chainloop trace init` installs the hooks of the selected agent. A second init changes nothing. `chainloop trace uninstall` deletes only the Chainloop hooks and keeps the other hooks of the agent. | Yes | Yes | Unknown | Yes | Yes | Yes | -| Trace run wrapper | `chainloop trace run -- ` gives the agent temporary hooks for one session. When the command exits, the configuration of the agent is the same as before. | Yes | Yes | Unknown | Yes | Yes | Yes | -| More than one agent in one repository | Two agents initialized in the same repository record their sessions separately, and each commit names the sessions of the agent that made it. | Unknown | Unknown | Unknown | Unknown | Unknown | Unknown | +| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | +|---------|---------------|-------------|--------|--------------|------------|---|---|---| +| Hook installation and deletion | `chainloop trace init` installs the hooks of the selected agent. A second init changes nothing. `chainloop trace uninstall` deletes only the Chainloop hooks and keeps the other hooks of the agent. | Yes | Yes | Unknown | Yes | Yes | Yes | Unknown | +| Trace run wrapper | `chainloop trace run -- ` gives the agent temporary hooks for one session. When the command exits, the configuration of the agent is the same as before. | Yes | Yes | Unknown | Yes | Yes | Yes | Unknown | +| More than one agent in one repository | Two agents initialized in the same repository record their sessions separately, and each commit names the sessions of the agent that made it. | Unknown | Unknown | Unknown | Unknown | Unknown | Unknown | Unknown | Why not Yes: - **Hook installation and deletion, and Trace run wrapper, OpenCode 1.x:** not verified yet. The end-to-end suite finds the values (spec issue-3635). +- **Hook installation and deletion, Trace run wrapper, Copilot:** not verified yet. The end-to-end suite finds the values (spec issue-3635). - **More than one agent in one repository, all agents:** not verified yet. The end-to-end suite needs a second agent to test it (spec issue-3635). ## Session collection What the session evidence holds about the conversation. -| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | -|---------|---------------|-------------|--------|--------------|------------|---|---| -| Transcript | The evidence holds the conversation (`raw_session`): the messages and the tool calls of the agent. | Yes | Yes | Partial | Partial | 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 | -| 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 | -| Model detection | The evidence names the primary model and the other models that the session used. | Yes | Partial | 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 | -| 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 | +| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | +|---------|---------------|-------------|--------|--------------|------------|---|---|---| +| Transcript | The evidence holds the conversation (`raw_session`): the messages and the tool calls of the agent. | Yes | Yes | Partial | Partial | Yes | Yes | Unknown | +| Token usage and cost | The evidence holds the tokens that the session used and their cost in USD. | Yes | No | Yes | Yes | Yes | Yes | 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 | Unknown | +| Model detection | The evidence names the primary model and the other models that the session used. | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | +| 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 | Why not Yes: @@ -68,6 +75,8 @@ Why not Yes: - **Model detection, Cursor:** the primary model comes from the session-start hook. The transcript does not tell the models, so the evidence does not list the other models. In auto mode, the hook names the model `default`, not the model that ran. - **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). +- **Transcript, token usage and cost, cache token accounting, model detection, and missed session start, Copilot:** not verified yet. The end-to-end suite finds the values. - **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). @@ -77,16 +86,16 @@ The cache accounting check reuses the edit-and-commit session, so it adds no age Which lines of a commit the AI wrote. -| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | -|---------|---------------|-------------|--------|--------------|------------|---|---| -| Line attribution | Each changed line of a commit is attributed to the AI or to a human, from a snapshot of each file before and after the agent edits it. An added line is AI when its content matches a line that an agent edit of the session wrote. A line that a human changed is human, also when a later agent edit keeps it. A whitespace-only change keeps the owner of the line. A removed line is AI only when an agent edit removed it. In a commit of more than one session, a line that only another session wrote or removed counts for neither side in this session's evidence (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | -| Partial commits | A commit that holds only part of the AI lines of a file credits the session with those lines. The other AI lines stay pending, and the next commit with them is credited to the session too (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | -| Generated line counts | The trace state keeps the lines that each agent edit added and removed, also the lines that never reach a commit. The evidence reports the totals of the session in `ai_generated_lines_added` and `ai_generated_lines_removed`. Files that `.gitattributes` marks `linguist-generated` do not count, as in the other line counts. A session with no commit sends no evidence, so it reports no totals (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | -| Shell changes attribution | Changes that the agent makes with shell commands (for example `sed`) are attributed to the AI too, not only changes made with the file tools. | Partial | Partial | Partial | Partial | Yes | Partial | -| Net contribution | The added lines of a session are the lines that its commits added and that are still in the commit that the push sends. A line that a later commit replaced does not count, and each line counts one time. The removed lines are the removals of the session's commits, less the lines that a commit of the session wrote. The line counts of each file are the sum of its AI and human lines, and a file that the session created stays created when a later commit of the session changes it (spec issue-3639, issue 3674). | Partial | Partial | Partial | Partial | Yes | Partial | -| Session updates | A later commit that replaces lines of a session sends the evidence of the session again at the next push, with the new numbers. A commit in no session that replaces lines of a session joins it: the commit list of the session holds the commit, and its replacing lines count as human (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | -| Line ranges | The line ranges of each file are positions in the file at the commit that the push sends. They cover the lines of the session that are still there, and each range says if its lines are AI or human. The AI ranges hold as many lines as the net AI lines added, and the human ranges as many lines as the net human lines added. A file that the pushed commit no longer holds has no ranges. A range with no attribution is an AI range at edit time. Older CLIs write only these ranges. This CLI writes them for a file that it cannot blame at the pushed commit, and for a file with edits from before line fingerprints (spec issue-3639, line ranges). | Partial | Partial | Partial | Partial | Yes | Partial | -| Renames and rewrites | The AI/human split survives a file rename, an amend, a rebase, a squash, and a cherry-pick. The lines match the trace state by content, and blame follows a renamed file to its lines from before the rename (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | +| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | +|---------|---------------|-------------|--------|--------------|------------|---|---|---| +| Line attribution | Each changed line of a commit is attributed to the AI or to a human, from a snapshot of each file before and after the agent edits it. An added line is AI when its content matches a line that an agent edit of the session wrote. A line that a human changed is human, also when a later agent edit keeps it. A whitespace-only change keeps the owner of the line. A removed line is AI only when an agent edit removed it. In a commit of more than one session, a line that only another session wrote or removed counts for neither side in this session's evidence (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | +| Partial commits | A commit that holds only part of the AI lines of a file credits the session with those lines. The other AI lines stay pending, and the next commit with them is credited to the session too (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | +| Generated line counts | The trace state keeps the lines that each agent edit added and removed, also the lines that never reach a commit. The evidence reports the totals of the session in `ai_generated_lines_added` and `ai_generated_lines_removed`. Files that `.gitattributes` marks `linguist-generated` do not count, as in the other line counts. A session with no commit sends no evidence, so it reports no totals (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | +| Shell changes attribution | Changes that the agent makes with shell commands (for example `sed`) are attributed to the AI too, not only changes made with the file tools. | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | +| Net contribution | The added lines of a session are the lines that its commits added and that are still in the commit that the push sends. A line that a later commit replaced does not count, and each line counts one time. The removed lines are the removals of the session's commits, less the lines that a commit of the session wrote. The line counts of each file are the sum of its AI and human lines, and a file that the session created stays created when a later commit of the session changes it (spec issue-3639, issue 3674). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | +| Session updates | A later commit that replaces lines of a session sends the evidence of the session again at the next push, with the new numbers. A commit in no session that replaces lines of a session joins it: the commit list of the session holds the commit, and its replacing lines count as human (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | +| Line ranges | The line ranges of each file are positions in the file at the commit that the push sends. They cover the lines of the session that are still there, and each range says if its lines are AI or human. The AI ranges hold as many lines as the net AI lines added, and the human ranges as many lines as the net human lines added. A file that the pushed commit no longer holds has no ranges. A range with no attribution is an AI range at edit time. Older CLIs write only these ranges. This CLI writes them for a file that it cannot blame at the pushed commit, and for a file with edits from before line fingerprints (spec issue-3639, line ranges). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | +| Renames and rewrites | The AI/human split survives a file rename, an amend, a rebase, a squash, and a cherry-pick. The lines match the trace state by content, and blame follows a renamed file to its lines from before the rename (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | Why not Yes: @@ -94,6 +103,7 @@ Why not Yes: - **Net contribution and line ranges, all agents:** the push finds the last writer of each line with `git blame`. A later commit that only re-indents a line takes the line, because blame sees a change. For Cursor, the limits of line attribution apply too. - **Session updates, all agents:** the update works only in the clone where the work happened, while the CLI keeps the trace state of the session (30 days), and only when the commits of the session are on the branch that the push sends. The push reads only the commits that are not on the default branch of the remote (`origin/HEAD`, or else `origin/main` or `origin/master`). After the commits of a session are pushed to that branch, a later commit does not update the session. - **Renames and rewrites, all agents:** this works only in the clone where the work happened. Git finds a rename only when the file keeps at least half of its content. Two pushed commits can rename a file one after the other. A later change to the file under its middle name does not send the session again. A rename inside an amend or a squash of the session commit loses the AI lines: the new commit creates the file under its new name, so no line of it matches the trace state (issue 3686). The limits of session updates apply too. For Cursor, the limits of line attribution apply too. +- **All code attribution features, Copilot:** not verified yet. The end-to-end suite finds the values. - **Shell changes attribution, all agents:** the hook before a shell command records only a hash of each file, not its content. The command's changes are the commits that it wrote itself, each against the `HEAD` it replaced, plus the worktree against the `HEAD` after the command. The `HEAD` reflog tells the command's own commits apart from moves to commits that it did not write, such as a rebase, a pull, a merge, a checkout or a reset: lines that such a move brings in do not count (PFM-8131). Both the files and the reftable ref storage are read. When the reflog is off, rewritten, or does not lead from the old `HEAD` to the new one, no commit of the command counts. Uncommitted lines that an earlier agent edit recorded are not recorded again, but uncommitted human lines of a file that the command changes count as AI. ## User experience @@ -102,11 +112,11 @@ What the user sees in the agent. The Codex welcome message and session link after push were verified manually in the interactive CLI 0.163.0. Codex runs its session-start hook after the first user message, so the welcome message appears then. The local-mode E2E suite does not verify these interactive messages. -| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | -|---------|---------------|-------------|--------|--------------|------------|---|---| -| Welcome message | At session start, the user sees a message that tells that Chainloop records the session, and where the evidence goes: the Chainloop project, or the on-disk path in local mode (spec issue-3582). | Yes | No | No | No | Unknown | Yes | -| Session link after push | After a `git push` that the agent runs, the user sees a link to the session in Chainloop. | Yes | No | No | No | Unknown | Yes | -| Credentials warning | At session start, in control-plane mode, the user is told when the control plane does not accept the CLI credentials (for example, an expired token), so the push will not upload the session. The hook uses the same check as `chainloop trace init`. An unreachable control plane, or a check that takes more than 2 seconds, shows no warning. | Yes | Partial | Partial | Partial | Unknown | Unknown | +| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | +|---------|---------------|-------------|--------|--------------|------------|---|---|---| +| Welcome message | At session start, the user sees a message that tells that Chainloop records the session, and where the evidence goes: the Chainloop project, or the on-disk path in local mode (spec issue-3582). | Yes | No | No | No | Unknown | Yes | No | +| Session link after push | After a `git push` that the agent runs, the user sees a link to the session in Chainloop. | Yes | No | No | No | Unknown | Yes | Unknown | +| Credentials warning | At session start, in control-plane mode, the user is told when the control plane does not accept the CLI credentials (for example, an expired token), so the push will not upload the session. The hook uses the same check as `chainloop trace init`. An unreachable control plane, or a check that takes more than 2 seconds, shows no warning. | Yes | Partial | Partial | Partial | Unknown | Unknown | Unknown | Why not Yes: @@ -116,22 +126,24 @@ Why not Yes: - **Welcome message, Cursor and OpenCode:** the provider gives the session-start context to the model only. It has no channel that shows a message to the user at session start, so the welcome message is dropped. - **Credentials warning, Cursor and OpenCode:** the provider has no channel to the user at session start. The model is told to tell the user, so the warning depends on the model. - **Session link after push, Cursor:** the `postToolUse` hook runs after a shell command, but its response has no field that Cursor shows to the user. The link stays pending until it expires. +- **Welcome message, Copilot:** Copilot documents no session-start output that it shows to the user. The provider gives the session-start context to the model only. +- **Session link after push and credentials warning, Copilot:** not verified yet. The link goes in the `additionalContext` of the `postToolUse` response, which the model reads. The credentials warning goes in the session-start instruction, so it depends on the model. - **Session link after push, OpenCode:** the plugin hook fires after a shell command, but the response that shows a message to the user is not verified yet. The link stays pending until it expires. ## Specs and skills What the session was asked to build, and which skills it used. -| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | -|---------|---------------|-------------|--------|--------------|------------|---|---| -| Spec capture instruction | At session start, the agent is told to capture the specs of the session (tickets, documents, plans, images) in the spec folder. A plan is captured only when it comes from an external source or from the plan mode of the agent: an agreement in the chat is not a plan. A pasted image is not captured, also when the agent has a file path for it. The agent tells the user in one line when it captures a file. | Yes | Yes | Yes | Yes | Yes | Yes | -| Spec capture reminder | At each user prompt, the agent is reminded to capture new or changed specs. | Yes | No | Yes | Yes | Yes | Unknown | -| 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 | -| 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 | -| 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 | -| Skills tracking | The evidence lists the skills that the session used, with a copy of each skill as it ran. | Yes | No | Partial | Partial | No | 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 | -| 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 | +| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | +|---------|---------------|-------------|--------|--------------|------------|---|---|---| +| Spec capture instruction | At session start, the agent is told to capture the specs of the session (tickets, documents, plans, images) in the spec folder. A plan is captured only when it comes from an external source or from the plan mode of the agent: an agreement in the chat is not a plan. A pasted image is not captured, also when the agent has a file path for it. The agent tells the user in one line when it captures a file. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | +| Spec capture reminder | At each user prompt, the agent is reminded to capture new or changed specs. | Yes | No | Yes | Yes | Yes | Unknown | No | +| 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 | Unknown | +| 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 | Unknown | +| 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 | Unknown | +| Skills tracking | The evidence lists the skills that the session used, with a copy of each skill as it ran. | Yes | No | Partial | Partial | No | 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 | Why not Yes: @@ -144,6 +156,9 @@ Why not Yes: - **Skills tracking, Codex:** tracks filesystem skills loaded through explicit Codex skill instructions or successful shell reads of one identified `SKILL.md`. The definition and supporting files use the shared skill snapshot and packaging pipeline. Multiple distinct skill paths in one tool call cannot be attributed reliably and are not tracked. Skills without a filesystem folder and child sessions are not captured. A snapshot first made at push carries a warning. - **Spec source pointers, Codex:** supports exact text results, native shell envelopes, recognized code-mode JSON envelopes, and complete file creation through native patches or literal patches in code mode. A code-mode write must be a single awaited `tools.apply_patch` call, optionally wrapped in `text`, with a literal argument or an immediately preceding `const` literal. Stored source files read with `cat` can also match within combined command output and native file-change records. Mixed or computed patches, other scripts, arbitrary output wrappers, transformed content, and other unsupported formats remain inline, so the table remains Partial. Earlier live sessions demonstrated this limit when the model trimmed the source's trailing newline. - **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. +- **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. +- **Other spec features, Copilot:** not verified yet. The end-to-end suite finds the values. - **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. @@ -153,27 +168,32 @@ Why not Yes: How the evidence is protected before it leaves the machine. -| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | -|---------|---------------|-------------|--------|--------------|------------|---|---| -| Secret redaction | Secrets in the session evidence and in the spec materials are replaced with a placeholder before upload. | Yes | Yes | Yes | Yes | Yes | Yes | -| Media skipped by redaction | The secret redaction does not scan base64 media (images, PDFs) in the transcript, so it is faster and does not break the media. | Yes | Unknown | Not applicable | Not applicable | Yes | Yes | -| Allow markers in redaction | A secret on a line that carries an inline `gitleaks:allow` or `betterleaks:allow` marker, such as a test fixture the agent read, is not redacted. The marker covers only its own line. | Yes | Yes | Yes | Yes | Yes | Yes | +| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | +|---------|---------------|-------------|--------|--------------|------------|---|---|---| +| Secret redaction | Secrets in the session evidence and in the spec materials are replaced with a placeholder before upload. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | +| Media skipped by redaction | The secret redaction does not scan base64 media (images, PDFs) in the transcript, so it is faster and does not break the media. | Yes | Unknown | Not applicable | Not applicable | Yes | Yes | Unknown | +| Allow markers in redaction | A secret on a line that carries an inline `gitleaks:allow` or `betterleaks:allow` marker, such as a test fixture the agent read, is not redacted. The marker covers only its own line. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | Why not Yes: - **Media skipped by redaction, Cursor:** the Cursor transcript holds no tool outputs, so a file that the agent reads leaves no media in it. A pasted image stays inline in the transcript, but it is not verified that it is in the base64 media shape that the redaction skips. The headless Cursor CLI cannot attach an image, so the end-to-end suite cannot check it. - **Media skipped by redaction, OpenCode:** the rebuilt transcript holds no media. +- **Security features, Copilot:** not verified yet. The end-to-end suite finds the values. ## Git integration How the sessions are linked to the commits and attested. -| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | -|---------|---------------|-------------|--------|--------------|------------|---|---| -| Commit trailer | Each commit gets a `Chainloop-Trace-Sessions` trailer with the sessions that contributed to it. | Yes | Yes | Yes | Yes | Yes | Yes | -| Attestation at push | In the default control-plane storage mode, the `pre-push` hook attests the sessions of the pushed commits to the control plane. | Yes | Yes | Yes | Yes | Unknown | Unknown | -| Local storage at push | In a repository with `traceStorage: LOCAL` in `.chainloop.yml`, the `pre-push` hook runs the same assembly as an attestation. It writes the session evidence set to the `local-sessions` folder of the trace directory and sends no attestation. It needs no control plane, login, or network. The stored set is equal to the upload of a push, except for the signature. A `statement.json` file indexes the set: the in-toto statement that a push would sign, with the `chainloop.dev/attestation/v0.2` predicate. It has no envelope and no signature, so it is not an attestation. `trace init --local` sets up the mode. `trace run --local` stores one wrapped session the same way, with no `.chainloop.yml` setting. Redaction is on by default. Set `CHAINLOOP_TRACE_NO_REDACT` to turn it off, for a trusted local store only (spec issue-3582). | Yes | Yes | Yes | Yes | Yes | Yes | -| Shell commands in another checkout | A session can work in a checkout other than the one it started in through shell commands only, for example in a fresh clone. The checkout is found from the command text: the target of `cd` or `pushd`, the path of `git -C`, and the folder that `git clone` or `gh repo clone` creates. The git hooks are installed there and the session is recorded there, the same as for a file tool edit in that checkout. A clone gets the git hooks only after the command that created it, so a commit in that same command does not carry the session. For OpenCode, a plugin installed by an earlier version does not send the command text: install the hooks again to update it. | Yes | Partial | Yes | Yes | Yes | Yes | +| Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | +|---------|---------------|-------------|--------|--------------|------------|---|---|---| +| Commit trailer | Each commit gets a `Chainloop-Trace-Sessions` trailer with the sessions that contributed to it. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | +| Attestation at push | In the default control-plane storage mode, the `pre-push` hook attests the sessions of the pushed commits to the control plane. | Yes | Yes | Yes | Yes | Unknown | Unknown | Unknown | +| Local storage at push | In a repository with `traceStorage: LOCAL` in `.chainloop.yml`, the `pre-push` hook runs the same assembly as an attestation. It writes the session evidence set to the `local-sessions` folder of the trace directory and sends no attestation. It needs no control plane, login, or network. The stored set is equal to the upload of a push, except for the signature. A `statement.json` file indexes the set: the in-toto statement that a push would sign, with the `chainloop.dev/attestation/v0.2` predicate. It has no envelope and no signature, so it is not an attestation. `trace init --local` sets up the mode. `trace run --local` stores one wrapped session the same way, with no `.chainloop.yml` setting. Redaction is on by default. Set `CHAINLOOP_TRACE_NO_REDACT` to turn it off, for a trusted local store only (spec issue-3582). | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | +| Shell commands in another checkout | A session can work in a checkout other than the one it started in through shell commands only, for example in a fresh clone. The checkout is found from the command text: the target of `cd` or `pushd`, the path of `git -C`, and the folder that `git clone` or `gh repo clone` creates. The git hooks are installed there and the session is recorded there, the same as for a file tool edit in that checkout. A clone gets the git hooks only after the command that created it, so a commit in that same command does not carry the session. For OpenCode, a plugin installed by an earlier version does not send the command text: install the hooks again to update it. | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | + +Why not Yes: + +- **All git integration features, Copilot:** not verified yet. The end-to-end suite finds the values. ### Switching storage modes @@ -200,19 +220,21 @@ Why not Yes: | Cursor | `.cursor/hooks.json` | Session start and end, `afterFileEdit`, and `preToolUse` and `postToolUse` for the `Shell` tool. The `preToolUse` hook always allows the command. The provider installs no prompt hook. | | Codex | `.codex/hooks.json` | `SessionStart`, `SessionEnd`, `UserPromptSubmit`, `PreToolUse` and `PostToolUse` for `Bash` and `apply_patch`. Patches use one snapshot per affected file, including both paths of a move. | | OpenCode | `.opencode/plugins/chainloop-trace.ts` | Session start and end, user prompt, and before and after each tool. One plugin covers both versions: `server()` for 1.x (1.3.4 or later) and `setup()` for 2. The provider picks the export command from `opencode --version`. | +| Copilot | `.github/hooks/chainloop-trace.json` (a file that Trace owns) | `sessionStart`, `sessionEnd`, and `preToolUse` and `postToolUse`. File tools `create` and `edit` use one snapshot per file. Shell tools `bash` and `powershell` use the working-tree snapshot. No `userPromptSubmitted` hook, because Copilot drops its output, and no `agentStop` hook, because it fires at each turn. Copilot CLI and the Copilot agent in VS Code read the same file. | | Pi | `.pi/extensions/chainloop-trace.ts` | Session start and selected shutdown reasons, session-tree changes, every user prompt, and before and after the `write`, `edit` and `bash` tools. | All agents share the git hooks `commit-msg`, `post-commit` and `pre-push`. ## End-to-end tests -The `e2e/` package checks the tables against real agents and models (spec issue-3635). It creates throwaway repositories and uses Trace in local storage mode. It currently runs the Claude Code, Cursor, OpenCode 2, Pi, and Codex columns. +The `e2e/` package checks the tables against real agents and models (spec issue-3635). It creates throwaway repositories and uses Trace in local storage mode. It currently runs the Claude Code, Cursor, OpenCode 2, Pi, Codex, and Copilot columns. 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 --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`. 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. - 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/claude/hooks.go b/app/cli/internal/trace/claude/hooks.go index 6fbe4840a..c1c9c151e 100644 --- a/app/cli/internal/trace/claude/hooks.go +++ b/app/cli/internal/trace/claude/hooks.go @@ -208,6 +208,11 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { Command string `json:"command"` } `json:"tool_input"` CursorVersion string `json:"cursor_version"` + // Timestamp and SessionIDCamel are in the payloads of the GitHub + // Copilot agent, which also runs these hooks. Claude Code sends + // neither. + Timestamp json.RawMessage `json:"timestamp"` + SessionIDCamel string `json:"sessionId"` } if err := json.Unmarshal(data, &raw); err != nil { return nil, err @@ -223,6 +228,13 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { return &trace.HookInput{}, nil } + // The GitHub Copilot agent runs the hooks of .claude/settings.json too. + // Its sessions belong to the copilot provider, so a Copilot payload + // yields an empty input and the session is recorded once. + if isCopilotPayload(raw.Timestamp, raw.SessionIDCamel, raw.TranscriptPath) { + return &trace.HookInput{}, nil + } + input := raw.HookInput if raw.ToolInput.FilePath != "" { input.FilePath = raw.ToolInput.FilePath @@ -233,6 +245,30 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { return &input, nil } +// isCopilotPayload reports whether the GitHub Copilot agent sent the payload. +// Copilot puts a timestamp on each payload and can send a camelCase session +// ID, and its transcript is an events.jsonl file in a session-state folder. +// Claude Code sends none of these. A timestamp counts only when the payload +// does not name a Claude Code transcript, so that a timestamp that a later +// Claude Code release adds does not hide its sessions. +func isCopilotPayload(timestamp json.RawMessage, sessionIDCamel, transcriptPath string) bool { + if sessionIDCamel != "" { + return true + } + if filepath.Base(transcriptPath) == "events.jsonl" && + filepath.Base(filepath.Dir(filepath.Dir(transcriptPath))) == "session-state" { + return true + } + return len(timestamp) > 0 && !isClaudeTranscript(transcriptPath) +} + +// isClaudeTranscript reports whether path is a session transcript in the +// Claude Code projects folder. +func isClaudeTranscript(path string) bool { + return filepath.Ext(path) == ".jsonl" && + filepath.Base(filepath.Dir(filepath.Dir(path))) == "projects" +} + func addHookEntry(hooks map[string]any, event, command, matcher string) bool { entries, _ := hooks[event].([]any) diff --git a/app/cli/internal/trace/claude/hooks_test.go b/app/cli/internal/trace/claude/hooks_test.go index b7940d397..52dc174b0 100644 --- a/app/cli/internal/trace/claude/hooks_test.go +++ b/app/cli/internal/trace/claude/hooks_test.go @@ -342,6 +342,55 @@ func TestReadHookInput(t *testing.T) { assert.Empty(t, input.SessionID, "Cursor-relayed events must yield an empty input") assert.Empty(t, input.FilePath) }) + + // The GitHub Copilot agent also runs the hooks of .claude/settings.json. + // Its payloads must yield an empty input, so the copilot provider owns + // the session and it is recorded once (spec issue-3800 R-003). + copilotPayloads := []struct { + name string + payload string + }{ + { + name: "snake_case form with a timestamp", + payload: `{"session_id":"s-1","hook_event_name":"PreToolUse","timestamp":"2026-04-08T15:04:05.000Z","cwd":"/repo","tool_name":"Write","tool_input":{"file_path":"/repo/README.md"}}`, + }, + { + name: "snake_case form with a numeric timestamp", + payload: `{"session_id":"s-1","hook_event_name":"PostToolUse","timestamp":1775596074872,"tool_name":"Bash","tool_input":{"command":"ls"}}`, + }, + { + name: "camelCase session ID", + payload: `{"sessionId":"s-1","session_id":"s-1","hook_event_name":"SessionStart"}`, + }, + { + name: "Copilot transcript path", + payload: `{"session_id":"s-1","hook_event_name":"Stop","transcript_path":"/home/u/.copilot/session-state/s-1/events.jsonl"}`, + }, + } + for _, tc := range copilotPayloads { + t.Run("bails on Copilot payloads: "+tc.name, func(t *testing.T) { + input, err := provider.ReadHookInput(bytes.NewBufferString(tc.payload)) + require.NoError(t, err) + assert.Empty(t, input.SessionID, "Copilot events must yield an empty input") + assert.Empty(t, input.FilePath) + assert.Empty(t, input.Command) + }) + } + + t.Run("keeps a Claude Code payload with a timestamp", func(t *testing.T) { + r := bytes.NewBufferString(`{"session_id":"s-1","hook_event_name":"PreToolUse","timestamp":"2026-04-08T15:04:05.000Z","transcript_path":"/home/u/.claude/projects/-repo/s-1.jsonl","tool_name":"Write","tool_input":{"file_path":"/repo/README.md"}}`) + input, err := provider.ReadHookInput(r) + require.NoError(t, err) + assert.Equal(t, "s-1", input.SessionID) + }) + + t.Run("keeps a Claude Code payload", func(t *testing.T) { + r := bytes.NewBufferString(`{"session_id":"s-1","hook_event_name":"PreToolUse","transcript_path":"/home/u/.claude/projects/-repo/s-1.jsonl","cwd":"/repo","tool_name":"Write","tool_input":{"file_path":"/repo/README.md"}}`) + input, err := provider.ReadHookInput(r) + require.NoError(t, err) + assert.Equal(t, "s-1", input.SessionID) + assert.Equal(t, "/repo/README.md", input.FilePath) + }) } func TestIsFileWritingTool(t *testing.T) { diff --git a/app/cli/internal/trace/copilot/copy.go b/app/cli/internal/trace/copilot/copy.go new file mode 100644 index 000000000..710ef9b57 --- /dev/null +++ b/app/cli/internal/trace/copilot/copy.go @@ -0,0 +1,193 @@ +// +// 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" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" +) + +// eventsFile is the name of the session event log in a session folder. +const eventsFile = "events.jsonl" + +// 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") + if home == "" { + userHome, err := os.UserHomeDir() + if err != nil { + return "" + } + home = filepath.Join(userHome, ".copilot") + } + return filepath.Join(home, "session-state") +} + +// CopySessionData refreshes the private copy of the session event log. The +// copy is atomic, so a failed copy keeps the previous one. A missing log is +// not an error. Only files inside the Copilot session-state folder are read. +func (p *Provider) CopySessionData(store *state.Store, loc trace.SessionLocation) error { + if store == nil || !state.ValidSessionID(loc.SessionID) { + return errors.New("copy Copilot session: invalid session") + } + rec, err := store.LoadSessionRecord(loc.SessionID) + if err != nil { + // The record is an optional hint. A damaged record must not stop a + // copy that is checked against the session-state folder. + rec = nil + } + root := sessionStateRoot() + if rec != nil && rec.CopilotStorageRoot != "" { + root = rec.CopilotStorageRoot + } + if root == "" { + return nil + } + + source := loc.TranscriptPath + if source != "" && !filepath.IsAbs(source) { + return errors.New("copy Copilot session: transcript path must be absolute") + } + if source == "" { + source = filepath.Join(root, loc.SessionID, eventsFile) + } + resolved, err := resolveInsideRoot(source, root) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + + src, err := os.Open(resolved) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + defer src.Close() + info, err := src.Stat() + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return errors.New("copy Copilot session: transcript is not a regular file") + } + + // The session.start record, not the path, owns the session identity. + scanner := bufio.NewScanner(src) + scanner.Buffer(make([]byte, 64*1024), maxHookPayloadBytes) + if !scanner.Scan() { + // Copilot writes session.start first. An empty log is not yet a session. + return nil + } + var header struct { + Type string `json:"type"` + Data struct { + SessionID string `json:"sessionId"` + } `json:"data"` + } + if json.Unmarshal(scanner.Bytes(), &header) != nil || header.Type != eventSessionStartRecord || header.Data.SessionID != loc.SessionID { + return errors.New("copy Copilot session: session ID mismatch") + } + if err := saveStorageRoot(store, rec, root); err != nil { + return fmt.Errorf("copy Copilot session: save storage root: %w", err) + } + + if _, err := src.Seek(0, io.SeekStart); err != nil { + return err + } + dir := store.RawSessionDir() + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".copilot-session-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + defer tmp.Close() + if _, err := io.Copy(tmp, src); err != nil { + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), state.RawSessionPath(dir, loc.SessionID)) +} + +// saveStorageRoot records the checked session-state folder, so that a push +// with another COPILOT_HOME still finds the log. +func saveStorageRoot(store *state.Store, rec *state.SessionRecord, root string) error { + if rec == nil || rec.CopilotStorageRoot != "" { + return nil + } + resolved, err := filepath.EvalSymlinks(root) + if err != nil { + return err + } + resolved, err = filepath.Abs(resolved) + if err != nil { + return err + } + // Reload, so that the writes of an overlapping hook are kept. + current, err := store.LoadSessionRecord(rec.SessionID) + if err != nil || current == nil || current.CopilotStorageRoot != "" { + return nil + } + current.CopilotStorageRoot = resolved + return store.SaveSessionRecord(current) +} + +// errOutsideStorage is returned for a transcript path outside the Copilot +// session-state folder. +var errOutsideStorage = errors.New("copy Copilot session: transcript outside Copilot session storage") + +// resolveInsideRoot returns path with its symbolic links resolved, after it +// checks that path is inside root, before and after the resolution. A path +// that does not exist returns an error that wraps os.ErrNotExist. +func resolveInsideRoot(path, root string) (string, error) { + if !within(filepath.Clean(path), filepath.Clean(root)) { + return "", errOutsideStorage + } + resolved, err := filepath.EvalSymlinks(path) + if err != nil { + return "", err + } + resolvedRoot, err := filepath.EvalSymlinks(root) + if err != nil { + return "", err + } + if !within(resolved, resolvedRoot) { + return "", errOutsideStorage + } + return resolved, nil +} + +func within(path, root string) bool { + rel, err := filepath.Rel(root, path) + return err == nil && filepath.IsLocal(rel) && rel != "." +} diff --git a/app/cli/internal/trace/copilot/hooks.go b/app/cli/internal/trace/copilot/hooks.go new file mode 100644 index 000000000..7e3e99e4b --- /dev/null +++ b/app/cli/internal/trace/copilot/hooks.go @@ -0,0 +1,371 @@ +// +// 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 ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" +) + +const ( + hookMarker = "chainloop trace hook copilot" + // settingsFile is the hook file that Trace owns. Copilot CLI and the + // Copilot agent in VS Code read every JSON file in .github/hooks, so + // Trace writes its own file instead of merging into a file of the user. + settingsFile = ".github/hooks/chainloop-trace.json" + + // Copilot hook event names, in the camelCase form of the hook file. + eventSessionStart = "sessionStart" + eventPreToolUse = "preToolUse" + eventPostToolUse = "postToolUse" + eventSessionEnd = "sessionEnd" + + // maxHookPayloadBytes caps hook payload reads. + maxHookPayloadBytes = 16 * 1024 * 1024 +) + +// fileWritingTools is the single source of truth for Copilot tools that write +// one file with a known path. +var fileWritingTools = []string{"create", "edit"} + +// commandTools are the Copilot tools that run a shell command. Their changes +// are captured with a before and after working-tree snapshot. +var commandTools = []string{"bash", "powershell"} + +// hookEvents lists the installed hooks. There is no agentStop hook: it fires +// at the end of each turn, and the session-end handler would end the session +// after the first turn. The push copies the transcript again anyway. There is +// no userPromptSubmitted hook either: Copilot drops its output. +var hookEvents = []struct { + event, command string +}{ + {eventSessionStart, hookMarker + " session-start"}, + {eventPreToolUse, hookMarker + " pre-tool-use"}, + {eventPostToolUse, hookMarker + " post-tool-use"}, + {eventSessionEnd, hookMarker + " session-end"}, +} + +// hookFile is the format of a Copilot hook file. +type hookFile struct { + Version int `json:"version"` + Hooks map[string][]hookEntry `json:"hooks"` +} + +type hookEntry struct { + Type string `json:"type"` + Bash string `json:"bash,omitempty"` + PowerShell string `json:"powershell,omitempty"` + Command string `json:"command,omitempty"` +} + +// guardPrefix is the part of a guarded command that comes before the wrapped +// command. trace.GuardHookCommand closes it with a single quote. +var guardPrefix = strings.TrimSuffix(trace.GuardHookCommand(""), "'") + +// isChainloopEntry reports whether a hook entry runs a Chainloop Trace hook, +// with or without the missing-CLI guard. +func isChainloopEntry(e hookEntry) bool { + command := e.Bash + if command == "" { + command = e.Command + } + if strings.HasPrefix(command, guardPrefix) && strings.HasSuffix(command, "'") { + command = strings.TrimSuffix(strings.TrimPrefix(command, guardPrefix), "'") + } + return strings.HasPrefix(command, hookMarker+" ") +} + +// SettingsFile returns the absolute path of the hook file that Trace owns. +func (p *Provider) SettingsFile(repoRoot string) string { + return filepath.Join(repoRoot, settingsFile) +} + +// InstallHooks writes the Trace hook file. +func (p *Provider) InstallHooks(repoRoot string) error { + return p.writeHookFile(repoRoot, true, false) +} + +// InstallHooksForTraceRun writes the hook file without session end. trace run +// ends the session itself, and it restores the previous file after the run, +// so it can replace a file that Trace does not own. +func (p *Provider) InstallHooksForTraceRun(repoRoot string) error { + return p.writeHookFile(repoRoot, false, true) +} + +func renderHookFile(includeSessionEnd bool) []byte { + f := hookFile{Version: 1, Hooks: map[string][]hookEntry{}} + for _, h := range hookEvents { + if h.event == eventSessionEnd && !includeSessionEnd { + continue + } + f.Hooks[h.event] = []hookEntry{{Type: "command", Bash: trace.GuardHookCommand(h.command)}} + } + content, _ := json.MarshalIndent(f, "", " ") + return append(content, '\n') +} + +func (p *Provider) writeHookFile(repoRoot string, includeSessionEnd, allowUnowned bool) error { + path := p.SettingsFile(repoRoot) + content := renderHookFile(includeSessionEnd) + + existing, owned, err := readOwnedHookFile(path) + switch { + case errors.Is(err, os.ErrNotExist): + case err != nil && !allowUnowned: + return fmt.Errorf("install Copilot hooks: %w", err) + case err == nil && bytes.Equal(existing, content): + return nil + case err == nil && !owned && !allowUnowned: + return fmt.Errorf("install Copilot hooks: %s holds hooks that Chainloop did not write", settingsFile) + } + + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return fmt.Errorf("install Copilot hooks: create directory: %w", err) + } + if err := os.WriteFile(path, content, 0o600); err != nil { + return fmt.Errorf("install Copilot hooks: write file: %w", err) + } + return nil +} + +// readOwnedHookFile reads the hook file and tells whether every hook in it +// is a Chainloop hook. A missing file returns an error that wraps +// os.ErrNotExist. +func readOwnedHookFile(path string) ([]byte, bool, error) { + info, err := os.Lstat(path) + if err != nil { + return nil, false, err + } + if !info.Mode().IsRegular() { + return nil, false, fmt.Errorf("%s is not a regular file", path) + } + content, err := os.ReadFile(path) + if err != nil { + return nil, false, err + } + var f hookFile + if err := json.Unmarshal(content, &f); err != nil { + return content, false, fmt.Errorf("parse %s: %w", path, err) + } + total, ours := 0, 0 + for _, entries := range f.Hooks { + for _, e := range entries { + total++ + if isChainloopEntry(e) { + ours++ + } + } + } + return content, total > 0 && total == ours, nil +} + +// UninstallHooks deletes the hook file, but only when every hook in it is a +// Chainloop hook. Other hook files are never touched. +func (p *Provider) UninstallHooks(repoRoot string) error { + path := p.SettingsFile(repoRoot) + _, owned, err := readOwnedHookFile(path) + if errors.Is(err, os.ErrNotExist) || err != nil || !owned { + // A file that cannot be read or holds user hooks stays as it is. + return nil + } + if err := os.Remove(path); err != nil { + return fmt.Errorf("uninstall Copilot hooks: %w", err) + } + return nil +} + +// HooksInstalled reports whether the hook file holds a Chainloop hook. +func (p *Provider) HooksInstalled(repoRoot string) (bool, error) { + content, err := os.ReadFile(p.SettingsFile(repoRoot)) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + var f hookFile + if json.Unmarshal(content, &f) != nil { + return false, nil + } + for _, entries := range f.Hooks { + if slices.ContainsFunc(entries, isChainloopEntry) { + return true, nil + } + } + return false, nil +} + +// hookPayload is the union of the two payload forms that the Copilot agent +// sends: camelCase keys from the hook file, and snake_case keys in the form +// that VS Code compatible hooks get. +type hookPayload struct { + SessionID string `json:"sessionId"` + SessionIDSnake string `json:"session_id"` + HookEventName string `json:"hook_event_name"` + HookEventNameCamel string `json:"hookEventName"` + Cwd string `json:"cwd"` + TranscriptPath string `json:"transcriptPath"` + TranscriptPathSnk string `json:"transcript_path"` + ToolName string `json:"toolName"` + ToolNameSnake string `json:"tool_name"` + ToolArgs json.RawMessage `json:"toolArgs"` + ToolInput json.RawMessage `json:"tool_input"` + // ToolCalls is the pre-tool form of older Copilot CLI releases: one + // hook for a batch of calls. + ToolCalls []struct { + Name string `json:"name"` + Args json.RawMessage `json:"args"` + } `json:"toolCalls"` +} + +// toolArgs are the arguments of the file and shell tools that Trace reads. +type toolArgs struct { + Path string `json:"path"` + Command string `json:"command"` +} + +// decodeToolArgs reads tool arguments that come as a JSON object, or as a +// JSON string that holds the object. +func decodeToolArgs(raw json.RawMessage) toolArgs { + var args toolArgs + if len(raw) == 0 { + return args + } + var text string + if json.Unmarshal(raw, &text) == nil { + raw = json.RawMessage(text) + } + _ = json.Unmarshal(raw, &args) + return args +} + +// ReadHookInput reads a Copilot hook payload in either form. +// +// Copilot sends no tool call ID in its post-tool payload, so the input never +// carries one: the pre and post hooks of a shell tool then share the +// snapshot key of the session (TRC-006). +func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { + data, err := io.ReadAll(io.LimitReader(r, maxHookPayloadBytes+1)) + if err != nil { + return nil, err + } + if len(data) > maxHookPayloadBytes { + return nil, errors.New("copilot hook payload exceeds size limit") + } + + var raw hookPayload + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + input := &trace.HookInput{ + SessionID: firstNonEmpty(raw.SessionID, raw.SessionIDSnake), + HookEventName: firstNonEmpty(raw.HookEventName, raw.HookEventNameCamel), + Cwd: raw.Cwd, + TranscriptPath: firstNonEmpty(raw.TranscriptPath, raw.TranscriptPathSnk), + ToolName: firstNonEmpty(raw.ToolName, raw.ToolNameSnake), + } + + if input.ToolName != "" { + args := raw.ToolArgs + if len(args) == 0 { + args = raw.ToolInput + } + p.setToolTarget(input, decodeToolArgs(args)) + return input, nil + } + + if len(raw.ToolCalls) > 0 { + p.readToolCalls(input, raw) + } + return input, nil +} + +func (p *Provider) setToolTarget(input *trace.HookInput, args toolArgs) { + switch { + case p.IsFileWritingTool(input.ToolName): + input.FilePath = absPath(args.Path, input.Cwd) + case p.IsCommandTool(input.ToolName): + input.Command = args.Command + } +} + +// readToolCalls maps a batch of calls to one input. File tools win over a +// shell tool, because their per-file snapshots are exact. Each later +// post-tool hook carries one call. +func (p *Provider) readToolCalls(input *trace.HookInput, raw hookPayload) { + var paths []string + for _, call := range raw.ToolCalls { + if !p.IsFileWritingTool(call.Name) { + continue + } + if input.ToolName == "" { + input.ToolName = call.Name + } + if path := absPath(decodeToolArgs(call.Args).Path, input.Cwd); path != "" && !slices.Contains(paths, path) { + paths = append(paths, path) + } + } + switch { + case len(paths) == 1: + input.FilePath = paths[0] + return + case len(paths) > 1: + input.FilePaths = paths + return + case input.ToolName != "": + return + } + + for _, call := range raw.ToolCalls { + if p.IsCommandTool(call.Name) { + input.ToolName = call.Name + input.Command = decodeToolArgs(call.Args).Command + return + } + } +} + +func absPath(path, cwd string) string { + if path == "" { + return "" + } + if !filepath.IsAbs(path) { + if !filepath.IsAbs(cwd) { + return "" + } + path = filepath.Join(cwd, path) + } + return filepath.Clean(path) +} + +func firstNonEmpty(values ...string) string { + for _, v := range values { + if v != "" { + return v + } + } + return "" +} diff --git a/app/cli/internal/trace/copilot/hooks_test.go b/app/cli/internal/trace/copilot/hooks_test.go new file mode 100644 index 000000000..4d11e396f --- /dev/null +++ b/app/cli/internal/trace/copilot/hooks_test.go @@ -0,0 +1,258 @@ +// +// 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/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func readHookFile(t *testing.T, repo string) hookFile { + t.Helper() + data, err := os.ReadFile(filepath.Join(repo, settingsFile)) + require.NoError(t, err) + var f hookFile + require.NoError(t, json.Unmarshal(data, &f)) + return f +} + +func TestInstallHooks(t *testing.T) { + p := New() + + t.Run("writes guarded hooks and is idempotent", func(t *testing.T) { + repo := t.TempDir() + require.NoError(t, p.InstallHooks(repo)) + first, err := os.ReadFile(p.SettingsFile(repo)) + require.NoError(t, err) + + f := readHookFile(t, repo) + assert.Equal(t, 1, f.Version) + for _, event := range []string{eventSessionStart, eventPreToolUse, eventPostToolUse, eventSessionEnd} { + require.Len(t, f.Hooks[event], 1, event) + entry := f.Hooks[event][0] + assert.Equal(t, "command", entry.Type) + assert.True(t, strings.HasPrefix(entry.Bash, guardPrefix), "hook %s must use the missing-CLI guard", event) + assert.True(t, isChainloopEntry(entry)) + } + assert.NotContains(t, f.Hooks, "agentStop") + assert.NotContains(t, f.Hooks, "userPromptSubmitted") + + require.NoError(t, p.InstallHooks(repo)) + second, err := os.ReadFile(p.SettingsFile(repo)) + require.NoError(t, err) + assert.Equal(t, first, second) + }) + + t.Run("trace run omits session end", func(t *testing.T) { + repo := t.TempDir() + require.NoError(t, p.InstallHooksForTraceRun(repo)) + f := readHookFile(t, repo) + assert.NotContains(t, f.Hooks, eventSessionEnd) + assert.Contains(t, f.Hooks, eventSessionStart) + + // A permanent install afterwards adds session end back. + require.NoError(t, p.InstallHooks(repo)) + assert.Contains(t, readHookFile(t, repo).Hooks, eventSessionEnd) + }) + + t.Run("refuses a file with user hooks, except for trace run", func(t *testing.T) { + repo := t.TempDir() + path := p.SettingsFile(repo) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + user := []byte(`{"version":1,"hooks":{"sessionStart":[{"type":"command","bash":"echo hi"}]}}`) + require.NoError(t, os.WriteFile(path, user, 0o600)) + + require.Error(t, p.InstallHooks(repo)) + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, user, got) + + require.NoError(t, p.InstallHooksForTraceRun(repo)) + }) + + t.Run("refuses a file that is not JSON", func(t *testing.T) { + repo := t.TempDir() + path := p.SettingsFile(repo) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte("not json"), 0o600)) + require.Error(t, p.InstallHooks(repo)) + }) + + t.Run("leaves other hook files alone", func(t *testing.T) { + repo := t.TempDir() + other := filepath.Join(repo, ".github", "hooks", "mine.json") + require.NoError(t, os.MkdirAll(filepath.Dir(other), 0o755)) + require.NoError(t, os.WriteFile(other, []byte(`{"version":1}`), 0o600)) + + require.NoError(t, p.InstallHooks(repo)) + require.NoError(t, p.UninstallHooks(repo)) + + got, err := os.ReadFile(other) + require.NoError(t, err) + assert.Equal(t, `{"version":1}`, string(got)) + assert.NoFileExists(t, p.SettingsFile(repo)) + }) +} + +func TestUninstallAndHooksInstalled(t *testing.T) { + p := New() + + cases := []struct { + name string + content string + wantInstalled bool + wantRemoved bool + }{ + {name: "no file", wantInstalled: false, wantRemoved: true}, + {name: "user hooks only", content: `{"version":1,"hooks":{"sessionStart":[{"type":"command","bash":"echo hi"}]}}`}, + { + name: "mixed hooks", + content: `{"version":1,"hooks":{"sessionStart":[{"type":"command","bash":"echo hi"},{"type":"command","bash":"chainloop trace hook copilot session-start"}]}}`, + wantInstalled: true, + }, + {name: "not JSON", content: "{"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := t.TempDir() + path := p.SettingsFile(repo) + if tc.content != "" { + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(tc.content), 0o600)) + } + + installed, err := p.HooksInstalled(repo) + require.NoError(t, err) + assert.Equal(t, tc.wantInstalled, installed) + + require.NoError(t, p.UninstallHooks(repo)) + if tc.wantRemoved { + assert.NoFileExists(t, path) + } else { + got, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, tc.content, string(got)) + } + }) + } + + t.Run("installed then uninstalled", func(t *testing.T) { + repo := t.TempDir() + require.NoError(t, p.InstallHooks(repo)) + installed, err := p.HooksInstalled(repo) + require.NoError(t, err) + assert.True(t, installed) + + require.NoError(t, p.UninstallHooks(repo)) + assert.NoFileExists(t, p.SettingsFile(repo)) + }) +} + +func TestReadHookInput(t *testing.T) { + p := New() + cwd := "/work/repo" + + cases := []struct { + name string + payload string + want trace.HookInput + }{ + { + name: "session start, CLI form", + payload: `{"sessionId":"s-1","timestamp":1775596038764,"cwd":"/work/repo","source":"new","initialPrompt":"hi"}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd}, + }, + { + name: "session start, VS Code form", + payload: `{"session_id":"s-1","hook_event_name":"SessionStart","timestamp":"2026-04-08T15:04:05.000Z","cwd":"/work/repo","transcript_path":"/home/u/.copilot/session-state/s-1/events.jsonl"}`, + want: trace.HookInput{SessionID: testHookSession, HookEventName: "SessionStart", Cwd: cwd, TranscriptPath: "/home/u/.copilot/session-state/s-1/events.jsonl"}, + }, + { + name: "post tool, create with object args", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolName":"create","toolArgs":{"path":"/work/repo/a.md","file_text":"x"},"toolResult":{"resultType":"success"}}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolCreate, FilePath: "/work/repo/a.md"}, + }, + { + name: "pre tool, edit with string args and relative path", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolName":"edit","toolArgs":"{\"path\":\"src/a.go\",\"old_str\":\"a\",\"new_str\":\"b\"}"}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: "edit", FilePath: "/work/repo/src/a.go"}, + }, + { + name: "shell tool", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolName":"bash","toolArgs":{"command":"mkdir x","description":"d"}}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolBash, Command: "mkdir x"}, + }, + { + name: "VS Code tool form", + payload: `{"session_id":"s-1","cwd":"/work/repo","tool_name":"bash","tool_input":{"command":"ls"}}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolBash, Command: "ls"}, + }, + { + name: "pre tool, batched calls of an older CLI", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCalls":[{"id":"t1","name":"report_intent","args":"{\"intent\":\"x\"}"},{"id":"t2","name":"create","args":"{\"path\":\"/work/repo/a.md\",\"file_text\":\"x\"}"},{"id":"t3","name":"edit","args":"{\"path\":\"b.md\"}"}]}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolCreate, FilePaths: []string{"/work/repo/a.md", "/work/repo/b.md"}}, + }, + { + name: "pre tool, batched shell call", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCalls":[{"id":"t1","name":"report_intent","args":"{}"},{"id":"t2","name":"bash","args":"{\"command\":\"go test\"}"}]}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolBash, Command: "go test"}, + }, + { + name: "other tool", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolName":"view","toolArgs":{"path":"/work/repo/a.md"}}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: "view"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := p.ReadHookInput(strings.NewReader(tc.payload)) + require.NoError(t, err) + assert.Equal(t, tc.want, *got) + }) + } + + t.Run("invalid JSON", func(t *testing.T) { + _, err := p.ReadHookInput(strings.NewReader("{")) + require.Error(t, err) + }) + + t.Run("payload over the size limit", func(t *testing.T) { + big := `{"sessionId":"s","prompt":"` + strings.Repeat("a", maxHookPayloadBytes) + `"}` + _, err := p.ReadHookInput(strings.NewReader(big)) + require.Error(t, err) + }) +} + +func TestToolLists(t *testing.T) { + p := New() + for _, tool := range []string{toolCreate, "edit"} { + assert.True(t, p.IsFileWritingTool(tool), tool) + assert.False(t, p.IsCommandTool(tool), tool) + } + for _, tool := range []string{toolBash, "powershell"} { + assert.True(t, p.IsCommandTool(tool), tool) + assert.False(t, p.IsFileWritingTool(tool), tool) + } + assert.False(t, p.IsFileWritingTool("view")) + assert.False(t, p.IsCommandTool("view")) +} diff --git a/app/cli/internal/trace/copilot/parse.go b/app/cli/internal/trace/copilot/parse.go new file mode 100644 index 000000000..7c4bd1db9 --- /dev/null +++ b/app/cli/internal/trace/copilot/parse.go @@ -0,0 +1,474 @@ +// +// 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" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "sort" + "time" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession" +) + +// Event types of the Copilot session event log. +const ( + eventSessionStartRecord = "session.start" + eventModelChange = "session.model_change" + eventUserMessage = "user.message" + eventAssistantMessage = "assistant.message" + eventToolComplete = "tool.execution_complete" + eventUsageRecord = "session.usage_record" + eventShutdown = "session.shutdown" + + // modelProvider is the vendor of the models as Trace records it: Copilot + // routes requests to models of several vendors. + modelProvider = "github-copilot" +) + +var knownEvents = map[string]bool{ + eventSessionStartRecord: true, + eventModelChange: true, + eventUserMessage: true, + eventAssistantMessage: true, + eventToolComplete: true, + eventUsageRecord: true, + eventShutdown: true, +} + +// tokenUsage is the usage of one model. Input excludes the cache tokens. +type tokenUsage struct { + Input, Output, CacheRead, CacheWrite int +} + +func (u *tokenUsage) add(o tokenUsage) { + u.Input += o.Input + u.Output += o.Output + u.CacheRead += o.CacheRead + u.CacheWrite += o.CacheWrite +} + +// copilotUsage is the usage form of the event log. Its input tokens include +// the cache tokens. +type copilotUsage struct { + Model string `json:"model"` + InputTokens int `json:"inputTokens"` + OutputTokens int `json:"outputTokens"` + CacheReadTokens int `json:"cacheReadTokens"` + CacheWriteTokens int `json:"cacheWriteTokens"` + APICallID string `json:"apiCallId"` +} + +func (u copilotUsage) normalized() tokenUsage { + return tokenUsage{ + Input: max(u.InputTokens-u.CacheReadTokens-u.CacheWriteTokens, 0), + Output: u.OutputTokens, + CacheRead: u.CacheReadTokens, + CacheWrite: u.CacheWriteTokens, + } +} + +type logEvent struct { + Type string `json:"type"` + ID string `json:"id"` + Timestamp string `json:"timestamp"` + AgentID string `json:"agentId"` + Data json.RawMessage `json:"data"` +} + +// eventData holds the fields of the event types that the parser reads. +type eventData struct { + SessionID string `json:"sessionId"` + CopilotVersion string `json:"copilotVersion"` + NewModel string `json:"newModel"` + Model string `json:"model"` + Content string `json:"content"` + ReasoningText string `json:"reasoningText"` + OutputTokens int `json:"outputTokens"` + ToolCallID string `json:"toolCallId"` + ToolRequests []struct { + ToolCallID string `json:"toolCallId"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + } `json:"toolRequests"` + Result *struct { + Content string `json:"content"` + } `json:"result"` + Usage *copilotUsage `json:"usage"` + CurrentModel string `json:"currentModel"` + ModelMetrics map[string]struct { + Usage copilotUsage `json:"usage"` + } `json:"modelMetrics"` +} + +// ParseSession reads only the private copy of the event log. Unknown event +// types stay in the raw session, because the format can change. +func (p *Provider) ParseSession(ctx context.Context, opts *trace.ParseOpts) (*aicodingsession.Evidence, error) { + if opts == nil || !state.ValidSessionID(opts.SessionID) { + return nil, errors.New("parse Copilot session: invalid options") + } + path, err := state.FindRawSessionFile(opts.SessionDir, opts.SessionID) + if err != nil { + return nil, err + } + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + d := aicodingsession.Data{ + SchemaVersion: "v2", + Agent: aicodingsession.Agent{Name: Name, Version: opts.AgentVersion}, + Session: aicodingsession.Session{ID: opts.SessionID}, + Model: &aicodingsession.Model{Primary: opts.Model, Provider: modelProvider}, + ToolsUsed: &aicodingsession.ToolsUsed{}, + Conversation: &aicodingsession.Conversation{}, + RawSession: map[string][]json.RawMessage{"main": {}}, + } + parser := newLogParser(&d) + + scanner := bufio.NewScanner(f) + scanner.Buffer(make([]byte, 64*1024), maxHookPayloadBytes) + line := 0 + for scanner.Scan() { + if err := ctx.Err(); err != nil { + return nil, err + } + line++ + raw := scanner.Bytes() + if len(raw) == 0 { + continue + } + raw = append(json.RawMessage(nil), raw...) + var e logEvent + if json.Unmarshal(raw, &e) != nil || e.Type == "" { + d.Warnings = append(d.Warnings, fmt.Sprintf("invalid Copilot event on line %d", line)) + continue + } + // Only the event types that the parser reads are decoded. Other + // types keep any shape, and stay in the raw session as they are. + var data eventData + if knownEvents[e.Type] && len(e.Data) > 0 && json.Unmarshal(e.Data, &data) != nil { + d.Warnings = append(d.Warnings, fmt.Sprintf("unreadable Copilot %s event on line %d", e.Type, line)) + d.RawSession["main"] = append(d.RawSession["main"], json.RawMessage(raw)) + continue + } + d.RawSession["main"] = append(d.RawSession["main"], rawEntry(e, data, raw, line)) + if err := parser.consume(e, data, line); err != nil { + return nil, err + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("read Copilot event log: %w", err) + } + if err := parser.finish(); err != nil { + return nil, err + } + return aicodingsession.NewEvidence(d), nil +} + +type usageRecord struct { + line int + model string + usage tokenUsage +} + +type logParser struct { + data *aicodingsession.Data + models map[string]int + tools map[string]int + calls map[string]bool + model string + first, last time.Time + haveHeader bool + shutdowns map[string]tokenUsage + lastShutdown int + records map[string]usageRecord + messageUsage map[string]tokenUsage +} + +func newLogParser(d *aicodingsession.Data) *logParser { + return &logParser{ + data: d, + models: map[string]int{}, + tools: map[string]int{}, + calls: map[string]bool{}, + model: d.Model.Primary, + shutdowns: map[string]tokenUsage{}, + records: map[string]usageRecord{}, + messageUsage: map[string]tokenUsage{}, + } +} + +func (p *logParser) noteModel(model string) { + if model == "" { + return + } + p.model = model + if _, ok := p.models[model]; !ok { + p.models[model] = 0 + } +} + +func (p *logParser) consume(e logEvent, data eventData, line int) error { + if at, err := time.Parse(time.RFC3339Nano, e.Timestamp); err == nil { + if p.first.IsZero() || at.Before(p.first) { + p.first = at + } + if p.last.IsZero() || at.After(p.last) { + p.last = at + } + } + + switch e.Type { + case eventSessionStartRecord: + if data.SessionID != p.data.Session.ID { + return errors.New("parse Copilot session: session ID mismatch") + } + p.haveHeader = true + if data.CopilotVersion != "" { + p.data.Agent.Version = data.CopilotVersion + } + case eventModelChange: + p.noteModel(data.NewModel) + case eventUserMessage: + if e.AgentID == "" { + p.data.Conversation.UserMessages++ + } + case eventAssistantMessage: + p.consumeAssistantMessage(e, data) + case eventToolComplete: + p.noteModel(data.Model) + case eventUsageRecord: + p.consumeUsageRecord(data, line) + case eventShutdown: + p.consumeShutdown(e, data, line) + } + return nil +} + +func (p *logParser) consumeAssistantMessage(e logEvent, data eventData) { + if e.AgentID == "" { + p.data.Conversation.AssistantMessages++ + } + if p.model != "" { + p.models[p.model]++ + } + for _, req := range data.ToolRequests { + if req.Name == "" || (req.ToolCallID != "" && p.calls[req.ToolCallID]) { + continue + } + p.tools[req.Name]++ + if req.ToolCallID != "" { + p.calls[req.ToolCallID] = true + } + } + if data.OutputTokens > 0 { + u := p.messageUsage[p.model] + u.Output += data.OutputTokens + p.messageUsage[p.model] = u + } +} + +func (p *logParser) consumeUsageRecord(data eventData, line int) { + if data.Usage == nil { + return + } + p.noteModel(data.Usage.Model) + key := data.Usage.APICallID + if key == "" { + key = fmt.Sprintf("line-%d", line) + } + // Copilot can write a record again; the latest copy wins. + p.records[key] = usageRecord{line: line, model: data.Usage.Model, usage: data.Usage.normalized()} +} + +// consumeShutdown adds a session summary. Only the main agent writes one, +// and its totals include the subagents. Each Copilot process writes one for +// its own segment of a resumed session. +func (p *logParser) consumeShutdown(e logEvent, data eventData, line int) { + if e.AgentID != "" || len(data.ModelMetrics) == 0 { + return + } + for model, m := range data.ModelMetrics { + u := p.shutdowns[model] + u.add(m.Usage.normalized()) + p.shutdowns[model] = u + if _, ok := p.models[model]; !ok { + p.models[model] = 0 + } + } + p.lastShutdown = line + if data.CurrentModel != "" { + p.data.Model.Primary = data.CurrentModel + } +} + +// usageByModel selects the token source: the shutdown totals, plus the +// records after the last shutdown; else the per-call records; else the +// output tokens of the messages, with a warning. +func (p *logParser) usageByModel() map[string]tokenUsage { + switch { + case len(p.shutdowns) > 0: + out := map[string]tokenUsage{} + for model, u := range p.shutdowns { + out[model] = u + } + for _, r := range p.records { + if r.line > p.lastShutdown { + u := out[r.model] + u.add(r.usage) + out[r.model] = u + } + } + return out + case len(p.records) > 0: + out := map[string]tokenUsage{} + for _, r := range p.records { + u := out[r.model] + u.add(r.usage) + out[r.model] = u + } + p.data.Warnings = append(p.data.Warnings, "Copilot event log has no session summary; token usage comes from the records of each call") + return out + case len(p.messageUsage) > 0: + p.data.Warnings = append(p.data.Warnings, "Copilot event log has no session summary; token usage has only the output tokens of each message") + return p.messageUsage + } + return nil +} + +func (p *logParser) finish() error { + if !p.haveHeader { + return errors.New("parse Copilot session: missing session.start event") + } + d := p.data + + if !p.first.IsZero() { + d.Session.StartedAt = p.first.UTC().Format(time.RFC3339) + d.Session.EndedAt = p.last.UTC().Format(time.RFC3339) + d.Session.DurationSeconds = int(p.last.Sub(p.first).Seconds()) + } + + for name := range p.models { + d.Model.ModelsUsed = append(d.Model.ModelsUsed, name) + } + sort.Strings(d.Model.ModelsUsed) + if d.Model.Primary == "" { + best := -1 + for _, name := range d.Model.ModelsUsed { + if p.models[name] > best { + d.Model.Primary = name + best = p.models[name] + } + } + } + if d.Model.Primary == "" { + d.Warnings = append(d.Warnings, "Copilot event log has no model information") + } + + for name, count := range p.tools { + d.ToolsUsed.Summary = append(d.ToolsUsed.Summary, aicodingsession.ToolSummary{ToolName: name, InvocationCount: count}) + d.ToolsUsed.TotalInvocations += count + } + sort.Slice(d.ToolsUsed.Summary, func(i, j int) bool { + a, b := d.ToolsUsed.Summary[i], d.ToolsUsed.Summary[j] + if a.InvocationCount != b.InvocationCount { + return a.InvocationCount > b.InvocationCount + } + return a.ToolName < b.ToolName + }) + d.Conversation.TotalMessages = d.Conversation.UserMessages + d.Conversation.AssistantMessages + + usage := p.usageByModel() + if len(usage) == 0 { + d.Warnings = append(d.Warnings, "Copilot event log has no token usage; cost is unavailable") + return nil + } + names := make([]string, 0, len(usage)) + for name := range usage { + names = append(names, name) + } + sort.Strings(names) + d.Usage = &aicodingsession.Usage{} + for _, name := range names { + u := usage[name] + d.Usage.InputTokens += u.Input + d.Usage.OutputTokens += u.Output + d.Usage.TotalTokens += u.Input + u.Output + d.Usage.CacheReadInputTokens += u.CacheRead + d.Usage.CacheCreationInputTokens += u.CacheWrite + model := name + if model == "" { + model = d.Model.Primary + } + d.Usage.EstimatedCostUSD += estimateCost(model, u, &d.Warnings) + } + d.Usage.EstimatedCostUSD = roundCost(d.Usage.EstimatedCostUSD) + return nil +} + +// rawEntry converts the messages and tool results to the shared line shape, +// so the session viewer can show them, and keeps the native event in +// source_event. Other events stay as Copilot wrote them. +func rawEntry(e logEvent, data eventData, raw json.RawMessage, line int) json.RawMessage { + entry := trace.RawSessionEntry{ + UUID: e.ID, + Timestamp: e.Timestamp, + SourceEvent: raw, + } + if entry.UUID == "" { + entry.UUID = fmt.Sprintf("copilot-event-%d", line) + } + + var blocks []any + switch e.Type { + case eventUserMessage: + entry.Type = trace.RoleUser + blocks = append(blocks, trace.RawSessionTextBlock{Type: "text", Text: data.Content}) + 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}) + } + for _, req := range data.ToolRequests { + blocks = append(blocks, trace.RawSessionToolUseBlock{Type: "tool_use", ID: req.ToolCallID, Name: req.Name, Input: req.Arguments}) + } + case eventToolComplete: + entry.Type = trace.RoleUser + content := "" + if data.Result != nil { + content = data.Result.Content + } + encoded, _ := json.Marshal(content) + blocks = append(blocks, trace.RawSessionToolResultBlock{Type: "tool_result", ToolUseID: data.ToolCallID, Content: encoded}) + default: + return raw + } + entry.Message.Role = entry.Type + entry.Message.Content, _ = json.Marshal(blocks) + return trace.MustRawSessionEntry(entry) +} diff --git a/app/cli/internal/trace/copilot/parse_test.go b/app/cli/internal/trace/copilot/parse_test.go new file mode 100644 index 000000000..7659ea2fd --- /dev/null +++ b/app/cli/internal/trace/copilot/parse_test.go @@ -0,0 +1,237 @@ +// +// 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/json" + "os" + "strings" + "testing" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + testSessionID = "b4257b63-a7e8-4e3f-9bf0-019c98db1744" + testHookSession = "s-1" + testModel = "gpt-5.4" + toolCreate = "create" + toolBash = "bash" +) + +const header = `{"type":"session.start","data":{"sessionId":"` + testSessionID + `","copilotVersion":"1.0.82"},"id":"h","timestamp":"2026-04-07T21:00:00Z"}` + +func parseLog(t *testing.T, content string) (*aicodingsession.Data, 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 + evidence, err := New().ParseSession(t.Context(), &trace.ParseOpts{SessionDir: dir, SessionID: testSessionID}) + if err != nil { + return nil, err + } + return &evidence.Data, nil +} + +func TestParseSessionFixture(t *testing.T) { + content, err := os.ReadFile("testdata/session.jsonl") + require.NoError(t, err) + d, err := parseLog(t, string(content)) + require.NoError(t, err) + + assert.Equal(t, Name, d.Agent.Name) + assert.Equal(t, "1.0.82", d.Agent.Version) + assert.Equal(t, testSessionID, d.Session.ID) + assert.Equal(t, "2026-04-07T21:07:18Z", d.Session.StartedAt) + assert.Equal(t, "2026-04-07T21:08:42Z", d.Session.EndedAt) + assert.Equal(t, 83, d.Session.DurationSeconds) + + assert.Equal(t, "claude-sonnet-4.6", d.Model.Primary) + assert.Equal(t, modelProvider, d.Model.Provider) + assert.Equal(t, []string{"claude-sonnet-4.6"}, d.Model.ModelsUsed) + + require.NotNil(t, d.Usage) + assert.Equal(t, 21106, d.Usage.InputTokens) + assert.Equal(t, 311, d.Usage.OutputTokens) + assert.Equal(t, 21417, d.Usage.TotalTokens) + assert.Equal(t, 41648, d.Usage.CacheReadInputTokens) + assert.Equal(t, 0, d.Usage.CacheCreationInputTokens) + assert.InDelta(t, 0.0805, d.Usage.EstimatedCostUSD, 1e-9) + + assert.Equal(t, 3, d.ToolsUsed.TotalInvocations) + assert.Equal(t, []aicodingsession.ToolSummary{ + {ToolName: toolBash, InvocationCount: 1}, + {ToolName: toolCreate, InvocationCount: 1}, + {ToolName: "report_intent", InvocationCount: 1}, + }, d.ToolsUsed.Summary) + + assert.Equal(t, 1, d.Conversation.UserMessages) + assert.Equal(t, 3, d.Conversation.AssistantMessages) + assert.Equal(t, 4, d.Conversation.TotalMessages) + assert.Empty(t, d.Warnings) + + lines := strings.Split(strings.TrimSpace(string(content)), "\n") + require.Len(t, d.RawSession["main"], len(lines)) + for _, line := range d.RawSession["main"] { + var obj map[string]any + require.NoError(t, json.Unmarshal(line, &obj), "each raw line is a JSON object") + } + + // A message becomes the shared line shape, with the native event kept. + var user trace.RawSessionEntry + require.NoError(t, json.Unmarshal(d.RawSession["main"][3], &user)) + assert.Equal(t, trace.RoleUser, user.Type) + assert.JSONEq(t, `[{"type":"text","text":"Create a test dir with a README"}]`, string(user.Message.Content)) + assert.NotEmpty(t, user.SourceEvent) + + var assistant trace.RawSessionEntry + require.NoError(t, json.Unmarshal(d.RawSession["main"][8], &assistant)) + assert.Equal(t, trace.RoleAssistant, assistant.Type) + assert.Contains(t, string(assistant.Message.Content), `"type":"tool_use"`) + assert.Contains(t, string(assistant.Message.Content), `"name":"create"`) + + // An event type that the parser does not read stays as Copilot wrote it. + assert.JSONEq(t, lines[1], string(d.RawSession["main"][1])) +} + +func TestParseSessionUsageSources(t *testing.T) { + cases := []struct { + name string + events string + wantInput int + wantOutput int + wantCache int + wantWarning string + wantNoUsage bool + wantPrimary string + }{ + { + name: "shutdown totals plus records after the last shutdown", + events: `{"type":"session.usage_record","data":{"usage":{"model":"gpt-5.4","inputTokens":1000,"outputTokens":50,"cacheReadTokens":800,"apiCallId":"c1"}}} +{"type":"session.shutdown","data":{"modelMetrics":{"gpt-5.4":{"requests":{"count":1},"usage":{"inputTokens":1000,"outputTokens":50,"cacheReadTokens":800,"cacheWriteTokens":0}}},"currentModel":"gpt-5.4"}} +{"type":"session.usage_record","data":{"usage":{"model":"gpt-5.4","inputTokens":100,"outputTokens":5,"cacheReadTokens":0,"apiCallId":"c2"}}}`, + wantInput: 300, wantOutput: 55, wantCache: 800, wantPrimary: testModel, + }, + { + name: "two shutdowns of a resumed session add up", + events: `{"type":"session.shutdown","data":{"modelMetrics":{"gpt-5.4":{"usage":{"inputTokens":100,"outputTokens":10}}}}} +{"type":"session.shutdown","data":{"modelMetrics":{"gpt-5.4":{"usage":{"inputTokens":200,"outputTokens":20}}}}}`, + wantInput: 300, wantOutput: 30, + }, + { + name: "a subagent shutdown is not counted", + events: `{"type":"session.shutdown","data":{"modelMetrics":{"gpt-5.4":{"usage":{"inputTokens":100,"outputTokens":10}}}}} +{"type":"session.shutdown","agentId":"sub-1","data":{"modelMetrics":{"gpt-5.4":{"usage":{"inputTokens":999,"outputTokens":999}}}}}`, + wantInput: 100, wantOutput: 10, + }, + { + name: "records only, a rewritten record counts once", + events: `{"type":"session.usage_record","data":{"usage":{"model":"gpt-5.4","inputTokens":500,"outputTokens":20,"cacheReadTokens":400,"apiCallId":"c3"}}} +{"type":"session.usage_record","data":{"usage":{"model":"gpt-5.4","inputTokens":500,"outputTokens":25,"cacheReadTokens":400,"apiCallId":"c3"}}} +{"type":"session.usage_record","agentId":"sub-1","data":{"usage":{"model":"gpt-5.4","inputTokens":300,"outputTokens":30,"apiCallId":"c4"}}}`, + wantInput: 400, wantOutput: 55, wantCache: 400, + wantWarning: "token usage comes from the records of each call", + }, + { + name: "message output tokens only", + events: `{"type":"session.model_change","data":{"newModel":"gpt-5.4"}} +{"type":"assistant.message","data":{"content":"hi","outputTokens":7}}`, + wantOutput: 7, wantWarning: "only the output tokens", wantPrimary: testModel, + }, + { + name: "no usage", + events: `{"type":"user.message","data":{"content":"hi"}}`, + wantNoUsage: true, wantWarning: "no token usage", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + d, err := parseLog(t, header+"\n"+tc.events+"\n") + require.NoError(t, err) + if tc.wantNoUsage { + assert.Nil(t, d.Usage) + } else { + require.NotNil(t, d.Usage) + assert.Equal(t, tc.wantInput, d.Usage.InputTokens) + assert.Equal(t, tc.wantOutput, d.Usage.OutputTokens) + assert.Equal(t, tc.wantInput+tc.wantOutput, d.Usage.TotalTokens) + assert.Equal(t, tc.wantCache, d.Usage.CacheReadInputTokens) + } + if tc.wantWarning != "" { + assert.True(t, containsWarning(d.Warnings, tc.wantWarning), "warnings %v", d.Warnings) + } + if tc.wantPrimary != "" { + assert.Equal(t, tc.wantPrimary, d.Model.Primary) + } + }) + } +} + +func TestParseSessionErrors(t *testing.T) { + t.Run("session ID mismatch", func(t *testing.T) { + _, err := parseLog(t, `{"type":"session.start","data":{"sessionId":"other"}}`+"\n") + require.Error(t, err) + }) + t.Run("missing session.start", func(t *testing.T) { + _, err := parseLog(t, `{"type":"user.message","data":{"content":"hi"}}`+"\n") + require.Error(t, err) + }) + t.Run("bad lines give warnings and stay readable", func(t *testing.T) { + d, err := parseLog(t, header+"\nnot json\n"+`{"type":"user.message","data":{"content":["unexpected"]}}`+"\n"+`{"type":"future.event","data":{"content":["any shape"]}}`+"\n") + require.NoError(t, err) + assert.True(t, containsWarning(d.Warnings, "invalid Copilot event on line 2"), "warnings %v", d.Warnings) + assert.True(t, containsWarning(d.Warnings, "unreadable Copilot user.message event on line 3"), "warnings %v", d.Warnings) + // The header, the unreadable message, and the future event stay. + assert.Len(t, d.RawSession["main"], 3) + }) + t.Run("missing copy", func(t *testing.T) { + _, err := New().ParseSession(t.Context(), &trace.ParseOpts{SessionDir: t.TempDir(), SessionID: testSessionID}) + require.Error(t, err) + }) +} + +func TestEstimateCost(t *testing.T) { + u := tokenUsage{Input: 1_000_000, Output: 1_000_000, CacheRead: 1_000_000} + cases := []struct { + model string + want float64 + wantWarning bool + }{ + {model: "claude-sonnet-4.6", want: 3 + 15 + 0.3}, + {model: "anthropic/claude-sonnet-4.6", want: 3 + 15 + 0.3}, + {model: testModel, want: 2.5 + 15 + 0.25}, + {model: "some-new-model", want: 3 + 15 + 0.3, wantWarning: true}, + } + for _, tc := range cases { + t.Run(tc.model, func(t *testing.T) { + var warnings []string + assert.InDelta(t, tc.want, estimateCost(tc.model, u, &warnings), 1e-9) + assert.Equal(t, tc.wantWarning, len(warnings) == 1) + }) + } +} + +func containsWarning(warnings []string, part string) bool { + for _, w := range warnings { + if strings.Contains(w, part) { + return true + } + } + return false +} diff --git a/app/cli/internal/trace/copilot/pricing.go b/app/cli/internal/trace/copilot/pricing.go new file mode 100644 index 000000000..efc99fa77 --- /dev/null +++ b/app/cli/internal/trace/copilot/pricing.go @@ -0,0 +1,77 @@ +// +// 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 ( + _ "embed" + "encoding/json" + "fmt" + "math" + "strings" +) + +type modelPricing struct { + Input float64 `json:"input"` + Cached float64 `json:"cached"` + Output float64 `json:"output"` + CacheWrite float64 `json:"cache_write"` +} + +//go:embed pricing.json +var pricingJSON []byte + +var prices struct { + Default string `json:"default_model"` + Models map[string]modelPricing `json:"models"` +} + +func init() { + if err := json.Unmarshal(pricingJSON, &prices); err != nil { + panic(fmt.Sprintf("copilot trace: invalid embedded pricing: %v", err)) + } + if _, ok := prices.Models[prices.Default]; !ok { + panic("copilot trace: missing default model price") + } +} + +// normalizeModel maps a Copilot model name to a key of the price table: +// lowercase, no vendor prefix, and dashes in place of dots +// ("claude-sonnet-4.6" becomes "claude-sonnet-4-6"). +func normalizeModel(model string) string { + name := strings.ToLower(model) + if i := strings.LastIndex(name, "/"); i >= 0 { + name = name[i+1:] + } + return strings.ReplaceAll(name, ".", "-") +} + +// estimateCost returns the API-price estimate for the usage of one model. +// Input tokens exclude the cache tokens. An unknown model uses the default +// price and adds a warning. +func estimateCost(model string, u tokenUsage, warnings *[]string) float64 { + price, ok := prices.Models[normalizeModel(model)] + if !ok { + price = prices.Models[prices.Default] + *warnings = append(*warnings, fmt.Sprintf("unknown Copilot model %q; cost estimated using %s pricing", model, prices.Default)) + } + writePrice := price.CacheWrite + if writePrice == 0 { + writePrice = price.Input + } + return (float64(u.Input)*price.Input + float64(u.CacheWrite)*writePrice + float64(u.CacheRead)*price.Cached + float64(u.Output)*price.Output) / 1e6 +} + +func roundCost(cost float64) float64 { return math.Round(cost*1e4) / 1e4 } diff --git a/app/cli/internal/trace/copilot/pricing.json b/app/cli/internal/trace/copilot/pricing.json new file mode 100644 index 000000000..7360acca2 --- /dev/null +++ b/app/cli/internal/trace/copilot/pricing.json @@ -0,0 +1,229 @@ +{ + "version": "2026-11-11", + "source": "The Claude Code and Codex price tables of this repository (Anthropic and OpenAI API list prices)", + "notes": "USD per million tokens. Copilot bills by subscription and premium requests, so this is an API-price estimate, not the Copilot bill. Model names are normalized: lowercase, no vendor prefix, dots replaced with dashes. Unknown models use the default with a warning.", + "default_model": "claude-sonnet-4-6", + "models": { + "claude-haiku-4-5": { + "input": 1.0, + "cached": 0.1, + "output": 5.0, + "cache_write": 1.25 + }, + "claude-opus-4": { + "input": 15.0, + "cached": 1.5, + "output": 75.0, + "cache_write": 18.75 + }, + "claude-opus-4-1": { + "input": 15.0, + "cached": 1.5, + "output": 75.0, + "cache_write": 18.75 + }, + "claude-opus-4-5": { + "input": 5.0, + "cached": 0.5, + "output": 25.0, + "cache_write": 6.25 + }, + "claude-opus-4-6": { + "input": 5.0, + "cached": 0.5, + "output": 25.0, + "cache_write": 6.25 + }, + "claude-opus-4-7": { + "input": 5.0, + "cached": 0.5, + "output": 25.0, + "cache_write": 6.25 + }, + "claude-opus-4-8": { + "input": 5.0, + "cached": 0.5, + "output": 25.0, + "cache_write": 6.25 + }, + "claude-opus-5": { + "input": 5.0, + "cached": 0.5, + "output": 25.0, + "cache_write": 6.25 + }, + "claude-opus-5-5": { + "input": 4.0, + "cached": 0.2, + "output": 20.0, + "cache_write": 5.0 + }, + "claude-sonnet-4": { + "input": 3.0, + "cached": 0.3, + "output": 15.0, + "cache_write": 3.75 + }, + "claude-sonnet-4-5": { + "input": 3.0, + "cached": 0.3, + "output": 15.0, + "cache_write": 3.75 + }, + "claude-sonnet-4-6": { + "input": 3.0, + "cached": 0.3, + "output": 15.0, + "cache_write": 3.75 + }, + "claude-sonnet-5": { + "input": 2.0, + "cached": 0.2, + "output": 10.0, + "cache_write": 2.5 + }, + "claude-sonnet-5-5": { + "input": 2.0, + "cached": 0.2, + "output": 10.0, + "cache_write": 2.5 + }, + "gpt-4-1": { + "input": 2.0, + "cached": 0.5, + "output": 8.0 + }, + "gpt-4-1-mini": { + "input": 0.4, + "cached": 0.1, + "output": 1.6 + }, + "gpt-4-1-nano": { + "input": 0.1, + "cached": 0.025, + "output": 0.4 + }, + "gpt-4o": { + "input": 2.5, + "cached": 1.25, + "output": 10.0 + }, + "gpt-4o-mini": { + "input": 0.15, + "cached": 0.075, + "output": 0.6 + }, + "gpt-5": { + "input": 1.25, + "cached": 0.125, + "output": 10.0 + }, + "gpt-5-1": { + "input": 1.25, + "cached": 0.125, + "output": 10.0 + }, + "gpt-5-2": { + "input": 1.75, + "cached": 0.175, + "output": 14.0 + }, + "gpt-5-3-codex": { + "input": 1.75, + "cached": 0.175, + "output": 14 + }, + "gpt-5-4": { + "input": 2.5, + "cached": 0.25, + "output": 15.0 + }, + "gpt-5-4-mini": { + "input": 0.75, + "cached": 0.075, + "output": 4.5 + }, + "gpt-5-4-nano": { + "input": 0.2, + "cached": 0.02, + "output": 1.25 + }, + "gpt-5-5": { + "input": 5.0, + "cached": 0.5, + "output": 30.0 + }, + "gpt-5-6-luna": { + "input": 0.2, + "cached": 0.02, + "output": 1.2, + "cache_write": 0.25 + }, + "gpt-5-6-sol": { + "input": 4.0, + "cached": 0.4, + "output": 20.0, + "cache_write": 5.0 + }, + "gpt-5-6-terra": { + "input": 2.0, + "cached": 0.2, + "output": 12.0, + "cache_write": 2.5 + }, + "gpt-5-mini": { + "input": 0.25, + "cached": 0.025, + "output": 2.0 + }, + "gpt-5-nano": { + "input": 0.05, + "cached": 0.005, + "output": 0.4 + }, + "gpt-6-1-sol": { + "input": 2.0, + "cached": 0.1, + "output": 10.0, + "cache_write": 2.5 + }, + "gpt-6-astra": { + "input": 10.0, + "cached": 1.0, + "output": 50.0, + "cache_write": 12.5 + }, + "gpt-6-luna": { + "input": 0.1, + "cached": 0.01, + "output": 0.5, + "cache_write": 0.125 + }, + "gpt-6-sol": { + "input": 2.0, + "cached": 0.2, + "output": 10.0, + "cache_write": 2.5 + }, + "o1": { + "input": 15.0, + "cached": 7.5, + "output": 60.0 + }, + "o3": { + "input": 2.0, + "cached": 0.5, + "output": 8.0 + }, + "o3-mini": { + "input": 1.1, + "cached": 0.55, + "output": 4.4 + }, + "o4-mini": { + "input": 1.1, + "cached": 0.275, + "output": 4.4 + } + } +} diff --git a/app/cli/internal/trace/copilot/provider.go b/app/cli/internal/trace/copilot/provider.go new file mode 100644 index 000000000..2fe57fcda --- /dev/null +++ b/app/cli/internal/trace/copilot/provider.go @@ -0,0 +1,149 @@ +// +// 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 captures GitHub Copilot sessions, from Copilot CLI and from +// the Copilot agent in VS Code, through the Copilot hook files and the +// session event log that Copilot keeps on disk. +package copilot + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "os" + "slices" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" +) + +// Name is the identifier stored in session records and evidence. +const Name = "copilot" + +var _ trace.Provider = (*Provider)(nil) + +// Provider connects GitHub Copilot to Trace. It holds no session state. +type Provider struct { + // out is where hook responses go. Nil means os.Stdout. + out io.Writer +} + +// New creates a Copilot provider. +func New() *Provider { return &Provider{} } + +// Name returns the provider identifier. +func (p *Provider) Name() string { return Name } + +// CaptureFileSnapshot stores the content of input.FilePath before a file +// tool runs. A missing file (a new file) is not an error. +func (p *Provider) CaptureFileSnapshot(store *state.Store, input *trace.HookInput) error { + if input == nil || input.FilePath == "" { + return nil + } + + content, err := os.ReadFile(input.FilePath) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("read %q: %w", input.FilePath, err) + } + + return store.SaveFileSnapshot(fileSnapshotKey(input), content) +} + +// ResolveBeforeContent returns the snapshot that CaptureFileSnapshot saved. +func (p *Provider) ResolveBeforeContent(store *state.Store, input *trace.HookInput, _ []byte) []byte { + if input == nil || input.FilePath == "" { + return nil + } + + snap, err := store.LoadFileSnapshot(fileSnapshotKey(input)) + if err != nil { + return nil + } + return snap +} + +// CleanupAfterEdit deletes the snapshot of the edit. +func (p *Provider) CleanupAfterEdit(store *state.Store, input *trace.HookInput) { + if input == nil || input.FilePath == "" { + return + } + store.DeleteFileSnapshot(fileSnapshotKey(input)) +} + +// fileSnapshotKey has no tool call ID, because Copilot sends none: the key is +// the session and the path (TRC-006). +func fileSnapshotKey(input *trace.HookInput) state.FileSnapshotKey { + return state.FileSnapshotKey{SessionID: input.SessionID, FilePath: input.FilePath} +} + +// IsFileWritingTool returns true if the named tool writes one file. +func (p *Provider) IsFileWritingTool(toolName string) bool { + return slices.Contains(fileWritingTools, toolName) +} + +// IsCommandTool returns true if the named tool runs a shell command. +func (p *Provider) IsCommandTool(toolName string) bool { + return slices.Contains(commandTools, toolName) +} + +// SupportsSessionStartBanner is false: Copilot documents no session-start +// output that it shows to the user. +func (p *Provider) SupportsSessionStartBanner() bool { return false } + +// SupportsSessionStartInstruction is true: Copilot adds the additionalContext +// of a sessionStart hook to the session. +func (p *Provider) SupportsSessionStartInstruction() bool { return true } + +// SupportsPromptReminder is false: Copilot drops the output of a +// userPromptSubmitted command hook. +func (p *Provider) SupportsPromptReminder() bool { return false } + +// AnnounceSessionStart gives the instruction to the model. +func (p *Provider) AnnounceSessionStart(msg trace.SessionStartMessage) error { + return p.writeContext(msg.Instruction) +} + +// AnnouncePromptSubmit does nothing: Copilot drops the output of the hook. +func (p *Provider) AnnouncePromptSubmit(string) error { return nil } + +// AnnounceToUser adds the message to the result of the tool, so the model +// sees it in the same turn and tells the user. +func (p *Provider) AnnounceToUser(msg string) error { + if msg == "" { + return nil + } + return p.writeContext("Tell the user the following, including any link verbatim: " + msg) +} + +// hookResponse is the output of a sessionStart or postToolUse hook. +type hookResponse struct { + AdditionalContext string `json:"additionalContext"` +} + +// writeContext writes one JSON document, or nothing for an empty context. +func (p *Provider) writeContext(context string) error { + if context == "" { + return nil + } + out := p.out + if out == nil { + out = os.Stdout + } + return json.NewEncoder(out).Encode(hookResponse{AdditionalContext: context}) +} diff --git a/app/cli/internal/trace/copilot/provider_test.go b/app/cli/internal/trace/copilot/provider_test.go new file mode 100644 index 000000000..2de8985b1 --- /dev/null +++ b/app/cli/internal/trace/copilot/provider_test.go @@ -0,0 +1,208 @@ +// +// 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 ( + "bytes" + "os" + "path/filepath" + "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 headerLine = `{"type":"session.start","data":{"sessionId":"` + testSessionID + `"}}` + "\n" + +// copilotHome makes a Copilot home with the event log of testSessionID and +// points COPILOT_HOME at it. It returns the session-state folder. +func copilotHome(t *testing.T, content string) string { + t.Helper() + home := t.TempDir() + t.Setenv("COPILOT_HOME", home) + root := filepath.Join(home, "session-state") + if content != "" { + dir := filepath.Join(root, testSessionID) + require.NoError(t, os.MkdirAll(dir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, eventsFile), []byte(content), 0o600)) + } + return root +} + +func newStore(t *testing.T) *state.Store { + t.Helper() + store := state.NewOutOfTreeStore(t.TempDir()) + require.NoError(t, store.SaveSessionRecord(&state.SessionRecord{SessionID: testSessionID, Provider: Name, Active: true})) + return store +} + +func copied(t *testing.T, store *state.Store) []byte { + t.Helper() + data, err := os.ReadFile(state.RawSessionPath(store.RawSessionDir(), testSessionID)) + if os.IsNotExist(err) { + return nil + } + require.NoError(t, err) + return data +} + +func TestCopySessionData(t *testing.T) { + p := New() + + t.Run("copies the log and saves the storage root", func(t *testing.T) { + root := copilotHome(t, headerLine+`{"type":"user.message"}`+"\n") + store := newStore(t) + require.NoError(t, p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID})) + assert.Equal(t, headerLine+`{"type":"user.message"}`+"\n", string(copied(t, store))) + + rec, err := store.LoadSessionRecord(testSessionID) + require.NoError(t, err) + want, err := filepath.EvalSymlinks(root) + require.NoError(t, err) + assert.Equal(t, want, rec.CopilotStorageRoot) + }) + + t.Run("a push with another COPILOT_HOME uses the stored root", func(t *testing.T) { + copilotHome(t, headerLine) + store := newStore(t) + require.NoError(t, p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID})) + + t.Setenv("COPILOT_HOME", t.TempDir()) + rec, err := store.LoadSessionRecord(testSessionID) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(rec.CopilotStorageRoot, testSessionID, eventsFile), []byte(headerLine+`{"type":"session.shutdown"}`+"\n"), 0o600)) + + require.NoError(t, p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID})) + assert.Contains(t, string(copied(t, store)), "session.shutdown") + }) + + t.Run("missing log is not an error", func(t *testing.T) { + copilotHome(t, "") + store := newStore(t) + require.NoError(t, p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID})) + assert.Nil(t, copied(t, store)) + }) + + t.Run("session ID mismatch keeps the previous copy", func(t *testing.T) { + root := copilotHome(t, headerLine) + store := newStore(t) + require.NoError(t, p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID})) + + other := `{"type":"session.start","data":{"sessionId":"other"}}` + "\n" + require.NoError(t, os.WriteFile(filepath.Join(root, testSessionID, eventsFile), []byte(other), 0o600)) + require.Error(t, p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID})) + assert.Equal(t, headerLine, string(copied(t, store))) + }) + + t.Run("transcript path outside session storage", func(t *testing.T) { + copilotHome(t, headerLine) + outside := filepath.Join(t.TempDir(), "events.jsonl") + require.NoError(t, os.WriteFile(outside, []byte(headerLine), 0o600)) + store := newStore(t) + err := p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID, TranscriptPath: outside}) + require.ErrorIs(t, err, errOutsideStorage) + assert.Nil(t, copied(t, store)) + }) + + t.Run("relative transcript path", func(t *testing.T) { + copilotHome(t, headerLine) + err := p.CopySessionData(newStore(t), trace.SessionLocation{SessionID: testSessionID, TranscriptPath: "events.jsonl"}) + require.Error(t, err) + }) + + t.Run("symbolic link out of session storage", func(t *testing.T) { + root := copilotHome(t, "") + outside := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(outside, eventsFile), []byte(headerLine), 0o600)) + require.NoError(t, os.MkdirAll(root, 0o755)) + require.NoError(t, os.Symlink(outside, filepath.Join(root, testSessionID))) + + store := newStore(t) + err := p.CopySessionData(store, trace.SessionLocation{SessionID: testSessionID}) + require.ErrorIs(t, err, errOutsideStorage) + assert.Nil(t, copied(t, store)) + }) + + t.Run("invalid session ID", func(t *testing.T) { + require.Error(t, p.CopySessionData(newStore(t), trace.SessionLocation{SessionID: "../x"})) + }) +} + +func TestAnnounce(t *testing.T) { + cases := []struct { + name string + run func(p *Provider) error + want string + }{ + { + name: "session start instruction", + run: func(p *Provider) error { + return p.AnnounceSessionStart(trace.SessionStartMessage{Banner: "banner", Instruction: "capture the spec"}) + }, + want: `{"additionalContext":"capture the spec"}` + "\n", + }, + { + name: "session start with no instruction", + run: func(p *Provider) error { return p.AnnounceSessionStart(trace.SessionStartMessage{Banner: "banner"}) }, + }, + { + name: "prompt reminder is dropped", + run: func(p *Provider) error { return p.AnnouncePromptSubmit("reminder") }, + }, + { + name: "announce to user", + run: func(p *Provider) error { return p.AnnounceToUser("https://example.com/s") }, + want: `{"additionalContext":"Tell the user the following, including any link verbatim: https://example.com/s"}` + "\n", + }, + { + name: "empty announce", + run: func(p *Provider) error { return p.AnnounceToUser("") }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + p := &Provider{out: &out} + require.NoError(t, tc.run(p)) + assert.Equal(t, tc.want, out.String()) + }) + } + + p := New() + assert.False(t, p.SupportsSessionStartBanner()) + assert.True(t, p.SupportsSessionStartInstruction()) + assert.False(t, p.SupportsPromptReminder()) +} + +func TestFileSnapshots(t *testing.T) { + p := New() + store := state.NewOutOfTreeStore(t.TempDir()) + file := filepath.Join(t.TempDir(), "a.txt") + require.NoError(t, os.WriteFile(file, []byte("before\n"), 0o600)) + input := &trace.HookInput{SessionID: testSessionID, FilePath: file} + + require.NoError(t, p.CaptureFileSnapshot(store, input)) + assert.Equal(t, "before\n", string(p.ResolveBeforeContent(store, input, nil))) + p.CleanupAfterEdit(store, input) + assert.Nil(t, p.ResolveBeforeContent(store, input, nil)) + + // A new file has no snapshot. + missing := &trace.HookInput{SessionID: testSessionID, FilePath: filepath.Join(t.TempDir(), "new.txt")} + require.NoError(t, p.CaptureFileSnapshot(store, missing)) + assert.Nil(t, p.ResolveBeforeContent(store, missing, nil)) +} diff --git a/app/cli/internal/trace/copilot/testdata/session.jsonl b/app/cli/internal/trace/copilot/testdata/session.jsonl new file mode 100644 index 000000000..0797cb1ab --- /dev/null +++ b/app/cli/internal/trace/copilot/testdata/session.jsonl @@ -0,0 +1,13 @@ +{"type":"session.start","data":{"sessionId":"b4257b63-a7e8-4e3f-9bf0-019c98db1744","version":1,"producer":"copilot-agent","copilotVersion":"1.0.82","startTime":"2026-04-07T21:07:18.764Z","context":{"cwd":"/work/repo","gitRoot":"/work/repo","branch":"main"}},"id":"e-start","timestamp":"2026-04-07T21:07:18.800Z","parentId":null} +{"type":"session.info","data":{"infoType":"folder_trust","message":"Folder /work/repo has been added to trusted folders."},"id":"e-info","timestamp":"2026-04-07T21:07:20.411Z","parentId":"e-start"} +{"type":"session.model_change","data":{"newModel":"claude-sonnet-4.6"},"id":"e-model","timestamp":"2026-04-07T21:07:20.500Z","parentId":"e-info"} +{"type":"user.message","data":{"content":"Create a test dir with a README","transformedContent":"2026-04-07T21:07:50.689Z\n\nCreate a test dir with a README","attachments":[],"interactionId":"i-1"},"id":"e-user","timestamp":"2026-04-07T21:07:50.690Z","parentId":"e-model"} +{"type":"assistant.turn_start","data":{"turnId":"0","interactionId":"i-1"},"id":"e-turn","timestamp":"2026-04-07T21:07:50.694Z","parentId":"e-user"} +{"type":"assistant.message","data":{"messageId":"m-1","content":"","toolRequests":[{"toolCallId":"t-intent","name":"report_intent","arguments":{"intent":"Creating test dir"},"type":"function"},{"toolCallId":"t-bash","name":"bash","arguments":{"command":"mkdir /work/repo/test","description":"Create dir"},"type":"function"}],"interactionId":"i-1","reasoningText":"Simple task.","outputTokens":166},"id":"e-a1","timestamp":"2026-04-07T21:07:54.800Z","parentId":"e-turn"} +{"type":"tool.execution_complete","data":{"toolCallId":"t-intent","model":"claude-sonnet-4.6","interactionId":"i-1","success":true,"result":{"content":"Intent logged"},"toolTelemetry":{}},"id":"e-t1","timestamp":"2026-04-07T21:07:54.872Z","parentId":"e-a1"} +{"type":"tool.execution_complete","data":{"toolCallId":"t-bash","model":"claude-sonnet-4.6","interactionId":"i-1","success":true,"result":{"content":"\n"},"toolTelemetry":{}},"id":"e-t2","timestamp":"2026-04-07T21:07:55.000Z","parentId":"e-t1"} +{"type":"assistant.message","data":{"messageId":"m-2","content":"","toolRequests":[{"toolCallId":"t-create","name":"create","arguments":{"path":"/work/repo/test/README.md","file_text":"# test\n"},"type":"function"}],"interactionId":"i-1","outputTokens":112},"id":"e-a2","timestamp":"2026-04-07T21:07:58.000Z","parentId":"e-t2"} +{"type":"tool.execution_complete","data":{"toolCallId":"t-create","model":"claude-sonnet-4.6","interactionId":"i-1","success":true,"result":{"content":"Created file /work/repo/test/README.md with 7 characters"},"toolTelemetry":{}},"id":"e-t3","timestamp":"2026-04-07T21:07:58.300Z","parentId":"e-a2"} +{"type":"assistant.message","data":{"messageId":"m-3","content":"Done. Created test/README.md.","toolRequests":[],"interactionId":"i-1","outputTokens":33},"id":"e-a3","timestamp":"2026-04-07T21:08:01.000Z","parentId":"e-t3"} +{"type":"assistant.turn_end","data":{"turnId":"0"},"id":"e-turn-end","timestamp":"2026-04-07T21:08:01.100Z","parentId":"e-a3"} +{"type":"session.shutdown","data":{"shutdownType":"routine","totalPremiumRequests":1,"modelMetrics":{"claude-sonnet-4.6":{"requests":{"count":3,"cost":1},"usage":{"inputTokens":62754,"outputTokens":311,"cacheReadTokens":41648,"cacheWriteTokens":0}}},"currentModel":"claude-sonnet-4.6"},"id":"e-shutdown","timestamp":"2026-04-07T21:08:42.761Z","parentId":"e-turn-end"} diff --git a/app/cli/internal/trace/e2e/config.yaml b/app/cli/internal/trace/e2e/config.yaml index 435ac5a5c..5c1b335e7 100644 --- a/app/cli/internal/trace/e2e/config.yaml +++ b/app/cli/internal/trace/e2e/config.yaml @@ -34,6 +34,14 @@ harnesses: version: "0.163.0" models: - openrouter/openai/gpt-6-luna + # Copilot CLI runs with COPILOT_HOME next to the workspace, so it has no + # stored login: it needs a token with Copilot access in + # COPILOT_GITHUB_TOKEN, GH_TOKEN or GITHUB_TOKEN. The Copilot agent in VS + # Code has no headless mode, so the suite does not run it. + Copilot: + version: "1.0.82" + models: + - claude-haiku-4.5 # Runs and pass threshold of a cell whose feature depends on the model # following an instruction (R-006, D-004). A cell of any other feature runs diff --git a/app/cli/internal/trace/e2e/copilot.go b/app/cli/internal/trace/e2e/copilot.go new file mode 100644 index 000000000..efb58e561 --- /dev/null +++ b/app/cli/internal/trace/e2e/copilot.go @@ -0,0 +1,188 @@ +// +// 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 e2e + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" +) + +// copilotHooksPath is the hook file that `trace init --copilot` writes. +const copilotHooksPath = ".github/hooks/chainloop-trace.json" + +// copilotSessionStartEvent is the hook event of the session start in +// 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. +type Copilot struct { + // Bin is the copilot executable. Empty means "copilot" from PATH. + Bin string +} + +func (c *Copilot) bin() string { + if c.Bin != "" { + return c.Bin + } + return "copilot" +} + +// Column implements Harness. +func (c *Copilot) Column() string { return "Copilot" } + +// TraceFlag implements Harness. +func (c *Copilot) TraceFlag() string { return "--copilot" } + +// Version implements Harness. +func (c *Copilot) Version(ctx context.Context) (string, error) { + out, err := exec.CommandContext(ctx, c.bin(), "--version").Output() //nolint:gosec // the harness binary under test // nosemgrep + if err != nil { + return "", fmt.Errorf("copilot --version: %w", err) + } + return parseCopilotVersion(out) +} + +// parseCopilotVersion reads the output of `copilot --version`: the first word +// that starts with a digit, for example "1.0.82" in "GitHub Copilot CLI +// 1.0.82.". +func parseCopilotVersion(out []byte) (string, error) { + for _, field := range strings.Fields(string(out)) { + field = strings.TrimSuffix(strings.TrimPrefix(field, "v"), ".") + if field != "" && field[0] >= '0' && field[0] <= '9' { + return field, nil + } + } + return "", errors.New("copilot --version: no version in the output") +} + +// Run implements Harness. It runs `copilot -p` and approves all tools, +// because a headless run cannot answer a permission question. +// +// COPILOT_HOME is a folder next to the workspace, so the configuration, the +// user hooks and the sessions of the user who runs the suite do not load or +// mix with the sessions of the suite. The Trace hooks run in the same +// environment, so the provider reads the session log from that folder too. +// The CLI then has no stored login: it reads a token from COPILOT_GITHUB_TOKEN, +// GH_TOKEN or GITHUB_TOKEN. +// +// 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 + } + + args := []string{ + "-p", req.Prompt, + "--allow-all-tools", + "--no-ask-user", + flagModel, req.Model, + } + + name := c.bin() + if len(req.Wrapper) > 0 { + name = req.Wrapper[0] + args = append(append(append([]string{}, req.Wrapper[1:]...), c.bin()), args...) + } + + cmd := exec.CommandContext(ctx, name, args...) //nolint:gosec // the harness binary under test, with the prompt of a scenario // nosemgrep + cmd.Dir = req.Dir + cmd.Env = append(slices.Clone(req.Env), "COPILOT_HOME="+home) + var stderr bytes.Buffer + cmd.Stderr = &stderr + + raw, err := cmd.Output() + if err != nil { + return &RunOutput{Raw: raw}, fmt.Errorf("copilot -p: %w: %s", err, strings.TrimSpace(stderr.String())) + } + return &RunOutput{Raw: raw}, nil +} + +// HookConfig implements Harness. Copilot reads every JSON file in +// .github/hooks, so the hook of the user is in its own file. +func (c *Copilot) HookConfig() HookConfig { + return HookConfig{ + Path: copilotHooksPath, + ChainloopMarker: "chainloop trace hook copilot", + UserPath: ".github/hooks/e2e-user.json", + UserConfig: `{ + "version": 1, + "hooks": { + "sessionEnd": [ + {"type": "command", "bash": "echo e2e-user-hook"} + ] + } +} +`, + UserMarker: userHookMarker, + } +} + +// DisableSessionStart implements Harness. It deletes the sessionStart entry +// from the Trace hook file and keeps the other entries as they are. +func (c *Copilot) DisableSessionStart(repo string) error { + path := filepath.Join(repo, copilotHooksPath) + data, err := os.ReadFile(path) + if err != nil { + return err + } + + var settings map[string]json.RawMessage + if err := json.Unmarshal(data, &settings); err != nil { + return fmt.Errorf("decode %s: %w", copilotHooksPath, err) + } + var hooks map[string]json.RawMessage + if err := json.Unmarshal(settings["hooks"], &hooks); err != nil { + return fmt.Errorf("decode the hooks of %s: %w", copilotHooksPath, err) + } + if _, ok := hooks[copilotSessionStartEvent]; !ok { + return fmt.Errorf("%s has no %s hook", copilotHooksPath, copilotSessionStartEvent) + } + delete(hooks, copilotSessionStartEvent) + + if settings["hooks"], err = json.Marshal(hooks); err != nil { + return err + } + if data, err = json.MarshalIndent(settings, "", " "); err != nil { + return err + } + return os.WriteFile(path, data, 0o600) +} + +// SkillPath implements Harness. Copilot finds project skills in +// .github/skills. +func (c *Copilot) SkillPath(name string) string { + return ".github/skills/" + name + "/SKILL.md" +} diff --git a/app/cli/internal/trace/e2e/copilot_test.go b/app/cli/internal/trace/e2e/copilot_test.go new file mode 100644 index 000000000..025dfbeab --- /dev/null +++ b/app/cli/internal/trace/e2e/copilot_test.go @@ -0,0 +1,83 @@ +// +// 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 e2e + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseCopilotVersion(t *testing.T) { + cases := []struct { + name string + out string + want string + wantErr bool + }{ + {name: "bare version", out: "1.0.82\n", want: "1.0.82"}, + {name: "named version", out: "GitHub Copilot CLI 1.0.82.\nCommit: abc123\n", want: "1.0.82"}, + {name: "v prefix", out: "copilot v1.1.0\n", want: "1.1.0"}, + {name: "empty", out: "\n", wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := parseCopilotVersion([]byte(tc.out)) + if tc.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } +} + +func TestCopilotDisableSessionStart(t *testing.T) { + repo := t.TempDir() + require.NoError(t, copilot.New().InstallHooks(repo)) + + h := &Copilot{} + require.NoError(t, h.DisableSessionStart(repo)) + + data, err := os.ReadFile(filepath.Join(repo, copilotHooksPath)) + require.NoError(t, err) + var settings struct { + Hooks map[string]json.RawMessage `json:"hooks"` + } + require.NoError(t, json.Unmarshal(data, &settings)) + assert.NotContains(t, settings.Hooks, copilotSessionStartEvent) + assert.Contains(t, settings.Hooks, "postToolUse") + + // The file stays a Chainloop file: uninstall still deletes it. + installed, err := copilot.New().HooksInstalled(repo) + require.NoError(t, err) + assert.True(t, installed) + + require.Error(t, h.DisableSessionStart(repo), "a second call finds no sessionStart hook") +} + +func TestCopilotHookConfigMarkers(t *testing.T) { + cfg := (&Copilot{}).HookConfig() + assert.Contains(t, cfg.UserConfig, cfg.UserMarker) + assert.NotContains(t, cfg.UserConfig, cfg.ChainloopMarker) + assert.NotEqual(t, cfg.Path, cfg.UserFile()) +} diff --git a/app/cli/internal/trace/e2e/e2e_test.go b/app/cli/internal/trace/e2e/e2e_test.go index 8cd975473..60b761d27 100644 --- a/app/cli/internal/trace/e2e/e2e_test.go +++ b/app/cli/internal/trace/e2e/e2e_test.go @@ -133,6 +133,7 @@ var harnesses = map[string]Harness{ "OpenCode 2": &OpenCode{Major: "2"}, "Pi": &Pi{}, "Codex": &Codex{}, + "Copilot": &Copilot{}, } // configuredHarnesses returns the adapters of the harnesses that the suite diff --git a/app/cli/internal/trace/providers/capabilities_test.go b/app/cli/internal/trace/providers/capabilities_test.go index f4c2ce10e..ea7058a6d 100644 --- a/app/cli/internal/trace/providers/capabilities_test.go +++ b/app/cli/internal/trace/providers/capabilities_test.go @@ -20,6 +20,7 @@ import ( "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/cursor" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/opencode" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" @@ -63,6 +64,7 @@ func TestSessionStartChannels(t *testing.T) { }, {provider: codex.Name, wantBanner: true, wantInstruction: true, wantReminder: true, why: "Codex surfaces systemMessage and supports additionalContext at session start and user prompt"}, {provider: pi.Name, wantBanner: true, wantInstruction: true, wantReminder: true, why: "Pi shows banners in its UI and injects the session instruction and prompt reminder through the project extension"}, + {provider: copilot.Name, wantBanner: false, wantInstruction: true, wantReminder: false, why: "Copilot adds the additionalContext of sessionStart to the session, documents no session-start output for the user, and drops the output of userPromptSubmitted"}, } for _, tc := range testCases { @@ -81,7 +83,7 @@ func TestSessionStartChannels(t *testing.T) { // without a decision recorded above, since the default zero value would // silently claim no support. func TestSessionStartChannelsCoverEveryProvider(t *testing.T) { - known := map[string]bool{claude.Name: true, cursor.Name: true, opencode.Name: true, codex.Name: true, pi.Name: true} + known := map[string]bool{claude.Name: true, cursor.Name: true, opencode.Name: true, codex.Name: true, pi.Name: true, copilot.Name: true} for _, p := range All() { assert.True(t, known[p.Name()], "provider %q has no session-start channel expectation", p.Name()) diff --git a/app/cli/internal/trace/providers/registry.go b/app/cli/internal/trace/providers/registry.go index 6c45fa1a7..c2c5da17c 100644 --- a/app/cli/internal/trace/providers/registry.go +++ b/app/cli/internal/trace/providers/registry.go @@ -23,6 +23,7 @@ import ( "github.com/chainloop-dev/chainloop/app/cli/internal/trace" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/claude" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/codex" + "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/cursor" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/opencode" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" @@ -41,6 +42,7 @@ var all = []trace.Provider{ opencode.New(), pi.New(), codex.New(), + copilot.New(), } // byName is a lookup-optimized view of all, built once at init. diff --git a/app/cli/internal/trace/state/session.go b/app/cli/internal/trace/state/session.go index 31e4bd31b..b84af472a 100644 --- a/app/cli/internal/trace/state/session.go +++ b/app/cli/internal/trace/state/session.go @@ -47,6 +47,10 @@ type SessionRecord struct { // CodexStorageRoot is the canonical Codex home validated while copying // this session. Later pushes can refresh it without the original CODEX_HOME. CodexStorageRoot string `json:"codex_storage_root,omitempty"` + // CopilotStorageRoot is the canonical Copilot session-state folder + // validated while copying this session. Later pushes can refresh it + // without the original COPILOT_HOME. + CopilotStorageRoot string `json:"copilot_storage_root,omitempty"` // Checkouts lists the roots of the other checkouts that this session // edited with a file tool, sorted. Shell hooks run in the session's own // checkout, and they also snapshot these checkouts, so that a command From f5ec9daab89fd99c6c2262efd5996fe472f69418 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 01:30:37 +0100 Subject: [PATCH 05/16] fix(trace): record Copilot apply_patch edits and verify end to end Copilot uses apply_patch for file edits with GPT models. The provider now records each file of the patch. It also reads the model of each message and of session start, and wraps non-object tool arguments for the session viewer. The e2e harness trusts the workspace folder, because Copilot CLI loads the repository hooks only in a trusted folder. trace init and the README tell users to trust the repository. The README Copilot column holds the results of Copilot CLI 1.0.109 with gpt-6.1-sol. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/cmd/trace_init.go | 2 +- app/cli/internal/trace/README.md | 61 ++++++------- app/cli/internal/trace/copilot/hooks.go | 96 ++++++++++++++++---- app/cli/internal/trace/copilot/hooks_test.go | 15 ++- app/cli/internal/trace/copilot/parse.go | 18 +++- app/cli/internal/trace/copilot/parse_test.go | 21 +++++ app/cli/internal/trace/e2e/config.yaml | 14 ++- app/cli/internal/trace/e2e/copilot.go | 9 +- 8 files changed, 176 insertions(+), 60 deletions(-) diff --git a/app/cli/cmd/trace_init.go b/app/cli/cmd/trace_init.go index 2df535303..df91b4fd6 100644 --- a/app/cli/cmd/trace_init.go +++ b/app/cli/cmd/trace_init.go @@ -398,7 +398,7 @@ func writeTraceHarnessNotes(w io.Writer, installed []trace.Provider) { case codex.Name: fmt.Fprintln(w, "For Codex, review and trust the installed hooks in Codex before starting work.") case copilot.Name: - fmt.Fprintln(w, "For Copilot, the hooks are in .github/hooks/chainloop-trace.json. Copilot CLI and the Copilot agent in VS Code both read it.") + fmt.Fprintln(w, "For Copilot, the hooks are in .github/hooks/chainloop-trace.json. Copilot CLI and the Copilot agent in VS Code both read it. Copilot CLI loads it only in a trusted folder: trust the repository when Copilot asks, or use --trust-folder for a prompt-mode run.") case pi.Name: fmt.Fprintln(w, "For Pi, review the project extension at .pi/extensions/chainloop-trace.ts before starting work. Interactive Pi asks to trust project files. Non-interactive runs need saved trust or --approve.") } diff --git a/app/cli/internal/trace/README.md b/app/cli/internal/trace/README.md index 4e1c9945c..edc5c9f65 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 …`. 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. 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. -The Copilot column starts at **Unknown**: the provider has unit tests, but the end-to-end suite has not run for it yet. 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 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 cells marked **No** are features that the provider does not implement. ## Setup @@ -40,14 +40,13 @@ How Trace is added to a repository and to an agent. | Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | |---------|---------------|-------------|--------|--------------|------------|---|---|---| -| Hook installation and deletion | `chainloop trace init` installs the hooks of the selected agent. A second init changes nothing. `chainloop trace uninstall` deletes only the Chainloop hooks and keeps the other hooks of the agent. | Yes | Yes | Unknown | Yes | Yes | Yes | Unknown | -| Trace run wrapper | `chainloop trace run -- ` gives the agent temporary hooks for one session. When the command exits, the configuration of the agent is the same as before. | Yes | Yes | Unknown | Yes | Yes | Yes | Unknown | +| Hook installation and deletion | `chainloop trace init` installs the hooks of the selected agent. A second init changes nothing. `chainloop trace uninstall` deletes only the Chainloop hooks and keeps the other hooks of the agent. | Yes | Yes | Unknown | Yes | Yes | Yes | Yes | +| Trace run wrapper | `chainloop trace run -- ` gives the agent temporary hooks for one session. When the command exits, the configuration of the agent is the same as before. | Yes | Yes | Unknown | Yes | Yes | Yes | Yes | | More than one agent in one repository | Two agents initialized in the same repository record their sessions separately, and each commit names the sessions of the agent that made it. | Unknown | Unknown | Unknown | Unknown | Unknown | Unknown | Unknown | Why not Yes: - **Hook installation and deletion, and Trace run wrapper, OpenCode 1.x:** not verified yet. The end-to-end suite finds the values (spec issue-3635). -- **Hook installation and deletion, Trace run wrapper, Copilot:** not verified yet. The end-to-end suite finds the values (spec issue-3635). - **More than one agent in one repository, all agents:** not verified yet. The end-to-end suite needs a second agent to test it (spec issue-3635). ## Session collection @@ -56,10 +55,10 @@ What the session evidence holds about the conversation. | Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | |---------|---------------|-------------|--------|--------------|------------|---|---|---| -| Transcript | The evidence holds the conversation (`raw_session`): the messages and the tool calls of the agent. | Yes | Yes | Partial | Partial | Yes | Yes | Unknown | -| Token usage and cost | The evidence holds the tokens that the session used and their cost in USD. | Yes | No | Yes | Yes | Yes | Yes | Unknown | +| 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 | -| Model detection | The evidence names the primary model and the other models that the session used. | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | +| 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 | @@ -76,7 +75,8 @@ 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). -- **Transcript, token usage and cost, cache token accounting, model detection, and missed session start, Copilot:** not verified yet. The end-to-end suite finds the values. +- **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). @@ -88,14 +88,14 @@ Which lines of a commit the AI wrote. | Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | |---------|---------------|-------------|--------|--------------|------------|---|---|---| -| Line attribution | Each changed line of a commit is attributed to the AI or to a human, from a snapshot of each file before and after the agent edits it. An added line is AI when its content matches a line that an agent edit of the session wrote. A line that a human changed is human, also when a later agent edit keeps it. A whitespace-only change keeps the owner of the line. A removed line is AI only when an agent edit removed it. In a commit of more than one session, a line that only another session wrote or removed counts for neither side in this session's evidence (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | -| Partial commits | A commit that holds only part of the AI lines of a file credits the session with those lines. The other AI lines stay pending, and the next commit with them is credited to the session too (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | -| Generated line counts | The trace state keeps the lines that each agent edit added and removed, also the lines that never reach a commit. The evidence reports the totals of the session in `ai_generated_lines_added` and `ai_generated_lines_removed`. Files that `.gitattributes` marks `linguist-generated` do not count, as in the other line counts. A session with no commit sends no evidence, so it reports no totals (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | -| Shell changes attribution | Changes that the agent makes with shell commands (for example `sed`) are attributed to the AI too, not only changes made with the file tools. | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | -| Net contribution | The added lines of a session are the lines that its commits added and that are still in the commit that the push sends. A line that a later commit replaced does not count, and each line counts one time. The removed lines are the removals of the session's commits, less the lines that a commit of the session wrote. The line counts of each file are the sum of its AI and human lines, and a file that the session created stays created when a later commit of the session changes it (spec issue-3639, issue 3674). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | -| Session updates | A later commit that replaces lines of a session sends the evidence of the session again at the next push, with the new numbers. A commit in no session that replaces lines of a session joins it: the commit list of the session holds the commit, and its replacing lines count as human (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | -| Line ranges | The line ranges of each file are positions in the file at the commit that the push sends. They cover the lines of the session that are still there, and each range says if its lines are AI or human. The AI ranges hold as many lines as the net AI lines added, and the human ranges as many lines as the net human lines added. A file that the pushed commit no longer holds has no ranges. A range with no attribution is an AI range at edit time. Older CLIs write only these ranges. This CLI writes them for a file that it cannot blame at the pushed commit, and for a file with edits from before line fingerprints (spec issue-3639, line ranges). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | -| Renames and rewrites | The AI/human split survives a file rename, an amend, a rebase, a squash, and a cherry-pick. The lines match the trace state by content, and blame follows a renamed file to its lines from before the rename (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | Unknown | +| Line attribution | Each changed line of a commit is attributed to the AI or to a human, from a snapshot of each file before and after the agent edits it. An added line is AI when its content matches a line that an agent edit of the session wrote. A line that a human changed is human, also when a later agent edit keeps it. A whitespace-only change keeps the owner of the line. A removed line is AI only when an agent edit removed it. In a commit of more than one session, a line that only another session wrote or removed counts for neither side in this session's evidence (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Yes | +| Partial commits | A commit that holds only part of the AI lines of a file credits the session with those lines. The other AI lines stay pending, and the next commit with them is credited to the session too (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Yes | +| Generated line counts | The trace state keeps the lines that each agent edit added and removed, also the lines that never reach a commit. The evidence reports the totals of the session in `ai_generated_lines_added` and `ai_generated_lines_removed`. Files that `.gitattributes` marks `linguist-generated` do not count, as in the other line counts. A session with no commit sends no evidence, so it reports no totals (spec issue-3639). | Yes | Partial | Yes | Yes | Yes | Yes | Yes | +| Shell changes attribution | Changes that the agent makes with shell commands (for example `sed`) are attributed to the AI too, not only changes made with the file tools. | Partial | Partial | Partial | Partial | Yes | Partial | Partial | +| Net contribution | The added lines of a session are the lines that its commits added and that are still in the commit that the push sends. A line that a later commit replaced does not count, and each line counts one time. The removed lines are the removals of the session's commits, less the lines that a commit of the session wrote. The line counts of each file are the sum of its AI and human lines, and a file that the session created stays created when a later commit of the session changes it (spec issue-3639, issue 3674). | Partial | Partial | Partial | Partial | Yes | Partial | Partial | +| Session updates | A later commit that replaces lines of a session sends the evidence of the session again at the next push, with the new numbers. A commit in no session that replaces lines of a session joins it: the commit list of the session holds the commit, and its replacing lines count as human (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | Partial | +| Line ranges | The line ranges of each file are positions in the file at the commit that the push sends. They cover the lines of the session that are still there, and each range says if its lines are AI or human. The AI ranges hold as many lines as the net AI lines added, and the human ranges as many lines as the net human lines added. A file that the pushed commit no longer holds has no ranges. A range with no attribution is an AI range at edit time. Older CLIs write only these ranges. This CLI writes them for a file that it cannot blame at the pushed commit, and for a file with edits from before line fingerprints (spec issue-3639, line ranges). | Partial | Partial | Partial | Partial | Yes | Partial | Partial | +| Renames and rewrites | The AI/human split survives a file rename, an amend, a rebase, a squash, and a cherry-pick. The lines match the trace state by content, and blame follows a renamed file to its lines from before the rename (spec issue-3639). | Partial | Partial | Partial | Partial | Yes | Partial | Partial | Why not Yes: @@ -103,7 +103,6 @@ Why not Yes: - **Net contribution and line ranges, all agents:** the push finds the last writer of each line with `git blame`. A later commit that only re-indents a line takes the line, because blame sees a change. For Cursor, the limits of line attribution apply too. - **Session updates, all agents:** the update works only in the clone where the work happened, while the CLI keeps the trace state of the session (30 days), and only when the commits of the session are on the branch that the push sends. The push reads only the commits that are not on the default branch of the remote (`origin/HEAD`, or else `origin/main` or `origin/master`). After the commits of a session are pushed to that branch, a later commit does not update the session. - **Renames and rewrites, all agents:** this works only in the clone where the work happened. Git finds a rename only when the file keeps at least half of its content. Two pushed commits can rename a file one after the other. A later change to the file under its middle name does not send the session again. A rename inside an amend or a squash of the session commit loses the AI lines: the new commit creates the file under its new name, so no line of it matches the trace state (issue 3686). The limits of session updates apply too. For Cursor, the limits of line attribution apply too. -- **All code attribution features, Copilot:** not verified yet. The end-to-end suite finds the values. - **Shell changes attribution, all agents:** the hook before a shell command records only a hash of each file, not its content. The command's changes are the commits that it wrote itself, each against the `HEAD` it replaced, plus the worktree against the `HEAD` after the command. The `HEAD` reflog tells the command's own commits apart from moves to commits that it did not write, such as a rebase, a pull, a merge, a checkout or a reset: lines that such a move brings in do not count (PFM-8131). Both the files and the reftable ref storage are read. When the reflog is off, rewritten, or does not lead from the old `HEAD` to the new one, no commit of the command counts. Uncommitted lines that an earlier agent edit recorded are not recorded again, but uncommitted human lines of a file that the command changes count as AI. ## User experience @@ -136,11 +135,11 @@ What the session was asked to build, and which skills it used. | Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | |---------|---------------|-------------|--------|--------------|------------|---|---|---| -| Spec capture instruction | At session start, the agent is told to capture the specs of the session (tickets, documents, plans, images) in the spec folder. A plan is captured only when it comes from an external source or from the plan mode of the agent: an agreement in the chat is not a plan. A pasted image is not captured, also when the agent has a file path for it. The agent tells the user in one line when it captures a file. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | +| Spec capture instruction | At session start, the agent is told to capture the specs of the session (tickets, documents, plans, images) in the spec folder. A plan is captured only when it comes from an external source or from the plan mode of the agent: an agreement in the chat is not a plan. A pasted image is not captured, also when the agent has a file path for it. The agent tells the user in one line when it captures a file. | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Spec capture reminder | At each user prompt, the agent is reminded to capture new or changed specs. | Yes | No | Yes | Yes | Yes | Unknown | No | -| 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 | Unknown | -| 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 | Unknown | -| 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 | Unknown | +| 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 | No | 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 | @@ -158,7 +157,6 @@ 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. - **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. -- **Other spec features, Copilot:** not verified yet. The end-to-end suite finds the values. - **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. @@ -170,15 +168,14 @@ How the evidence is protected before it leaves the machine. | Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | |---------|---------------|-------------|--------|--------------|------------|---|---|---| -| Secret redaction | Secrets in the session evidence and in the spec materials are replaced with a placeholder before upload. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | -| Media skipped by redaction | The secret redaction does not scan base64 media (images, PDFs) in the transcript, so it is faster and does not break the media. | Yes | Unknown | Not applicable | Not applicable | Yes | Yes | Unknown | -| Allow markers in redaction | A secret on a line that carries an inline `gitleaks:allow` or `betterleaks:allow` marker, such as a test fixture the agent read, is not redacted. The marker covers only its own line. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | +| Secret redaction | Secrets in the session evidence and in the spec materials are replaced with a placeholder before upload. | Yes | Yes | Yes | Yes | Yes | Yes | Yes | +| Media skipped by redaction | The secret redaction does not scan base64 media (images, PDFs) in the transcript, so it is faster and does not break the media. | Yes | Unknown | Not applicable | Not applicable | Yes | Yes | Yes | +| Allow markers in redaction | A secret on a line that carries an inline `gitleaks:allow` or `betterleaks:allow` marker, such as a test fixture the agent read, is not redacted. The marker covers only its own line. | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Why not Yes: - **Media skipped by redaction, Cursor:** the Cursor transcript holds no tool outputs, so a file that the agent reads leaves no media in it. A pasted image stays inline in the transcript, but it is not verified that it is in the base64 media shape that the redaction skips. The headless Cursor CLI cannot attach an image, so the end-to-end suite cannot check it. - **Media skipped by redaction, OpenCode:** the rebuilt transcript holds no media. -- **Security features, Copilot:** not verified yet. The end-to-end suite finds the values. ## Git integration @@ -186,14 +183,14 @@ How the sessions are linked to the commits and attested. | Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | |---------|---------------|-------------|--------|--------------|------------|---|---|---| -| Commit trailer | Each commit gets a `Chainloop-Trace-Sessions` trailer with the sessions that contributed to it. | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | +| Commit trailer | Each commit gets a `Chainloop-Trace-Sessions` trailer with the sessions that contributed to it. | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Attestation at push | In the default control-plane storage mode, the `pre-push` hook attests the sessions of the pushed commits to the control plane. | Yes | Yes | Yes | Yes | Unknown | Unknown | Unknown | -| Local storage at push | In a repository with `traceStorage: LOCAL` in `.chainloop.yml`, the `pre-push` hook runs the same assembly as an attestation. It writes the session evidence set to the `local-sessions` folder of the trace directory and sends no attestation. It needs no control plane, login, or network. The stored set is equal to the upload of a push, except for the signature. A `statement.json` file indexes the set: the in-toto statement that a push would sign, with the `chainloop.dev/attestation/v0.2` predicate. It has no envelope and no signature, so it is not an attestation. `trace init --local` sets up the mode. `trace run --local` stores one wrapped session the same way, with no `.chainloop.yml` setting. Redaction is on by default. Set `CHAINLOOP_TRACE_NO_REDACT` to turn it off, for a trusted local store only (spec issue-3582). | Yes | Yes | Yes | Yes | Yes | Yes | Unknown | -| Shell commands in another checkout | A session can work in a checkout other than the one it started in through shell commands only, for example in a fresh clone. The checkout is found from the command text: the target of `cd` or `pushd`, the path of `git -C`, and the folder that `git clone` or `gh repo clone` creates. The git hooks are installed there and the session is recorded there, the same as for a file tool edit in that checkout. A clone gets the git hooks only after the command that created it, so a commit in that same command does not carry the session. For OpenCode, a plugin installed by an earlier version does not send the command text: install the hooks again to update it. | Yes | Partial | Yes | Yes | Yes | Yes | Unknown | +| Local storage at push | In a repository with `traceStorage: LOCAL` in `.chainloop.yml`, the `pre-push` hook runs the same assembly as an attestation. It writes the session evidence set to the `local-sessions` folder of the trace directory and sends no attestation. It needs no control plane, login, or network. The stored set is equal to the upload of a push, except for the signature. A `statement.json` file indexes the set: the in-toto statement that a push would sign, with the `chainloop.dev/attestation/v0.2` predicate. It has no envelope and no signature, so it is not an attestation. `trace init --local` sets up the mode. `trace run --local` stores one wrapped session the same way, with no `.chainloop.yml` setting. Redaction is on by default. Set `CHAINLOOP_TRACE_NO_REDACT` to turn it off, for a trusted local store only (spec issue-3582). | Yes | Yes | Yes | Yes | Yes | Yes | Yes | +| Shell commands in another checkout | A session can work in a checkout other than the one it started in through shell commands only, for example in a fresh clone. The checkout is found from the command text: the target of `cd` or `pushd`, the path of `git -C`, and the folder that `git clone` or `gh repo clone` creates. The git hooks are installed there and the session is recorded there, the same as for a file tool edit in that checkout. A clone gets the git hooks only after the command that created it, so a commit in that same command does not carry the session. For OpenCode, a plugin installed by an earlier version does not send the command text: install the hooks again to update it. | Yes | Partial | Yes | Yes | Yes | Yes | Yes | Why not Yes: -- **All git integration features, Copilot:** not verified yet. The end-to-end suite finds the values. +- **Attestation at push, Copilot:** this check needs a control plane. The suite uses local storage only. ### Switching storage modes @@ -234,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 --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`. 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 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. - 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/hooks.go b/app/cli/internal/trace/copilot/hooks.go index 7e3e99e4b..e47a92c3f 100644 --- a/app/cli/internal/trace/copilot/hooks.go +++ b/app/cli/internal/trace/copilot/hooks.go @@ -48,7 +48,14 @@ const ( // fileWritingTools is the single source of truth for Copilot tools that write // one file with a known path. -var fileWritingTools = []string{"create", "edit"} +// +// create and edit are the file tools of Claude models. apply_patch is the +// file tool of GPT models: its argument is the patch text, which can change +// several files. +var fileWritingTools = []string{"create", "edit", toolApplyPatch} + +// toolApplyPatch is the Copilot tool that applies a patch. +const toolApplyPatch = "apply_patch" // commandTools are the Copilot tools that run a shell command. Their changes // are captured with a before and after working-tree snapshot. @@ -263,9 +270,10 @@ func decodeToolArgs(raw json.RawMessage) toolArgs { // ReadHookInput reads a Copilot hook payload in either form. // -// Copilot sends no tool call ID in its post-tool payload, so the input never -// carries one: the pre and post hooks of a shell tool then share the -// snapshot key of the session (TRC-006). +// The pre-tool payload of a batch of calls cannot pair one call with its +// post-tool payload, so the input never carries a tool call ID, also when +// the post-tool payload has one. The pre and post hooks of a shell tool then +// share the snapshot key of the session (TRC-006). func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { data, err := io.ReadAll(io.LimitReader(r, maxHookPayloadBytes+1)) if err != nil { @@ -293,7 +301,7 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { if len(args) == 0 { args = raw.ToolInput } - p.setToolTarget(input, decodeToolArgs(args)) + p.setToolTarget(input, args) return input, nil } @@ -303,13 +311,69 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { return input, nil } -func (p *Provider) setToolTarget(input *trace.HookInput, args toolArgs) { +func (p *Provider) setToolTarget(input *trace.HookInput, args json.RawMessage) { switch { case p.IsFileWritingTool(input.ToolName): - input.FilePath = absPath(args.Path, input.Cwd) + setPaths(input, toolPaths(input.ToolName, args, input.Cwd)) case p.IsCommandTool(input.ToolName): - input.Command = args.Command + input.Command = decodeToolArgs(args).Command + } +} + +// setPaths sets FilePath for one path, or FilePaths for several, so the +// handlers snapshot each file of a tool that changes several files. +func setPaths(input *trace.HookInput, paths []string) { + switch len(paths) { + case 0: + case 1: + input.FilePath = paths[0] + default: + input.FilePaths = paths + } +} + +// toolPaths returns the absolute paths that a file tool writes. +func toolPaths(tool string, args json.RawMessage, cwd string) []string { + if tool == toolApplyPatch { + return patchPaths(patchText(args), cwd) } + if path := absPath(decodeToolArgs(args).Path, cwd); path != "" { + return []string{path} + } + return nil +} + +// patchText returns the patch of an apply_patch call: a JSON string, or an +// object with the patch in its input field. +func patchText(args json.RawMessage) string { + var text string + if json.Unmarshal(args, &text) == nil { + return text + } + var object struct { + Input string `json:"input"` + } + _ = json.Unmarshal(args, &object) + return object.Input +} + +// patchPaths lists the files of a patch, with both sides of a move, so that +// a deletion and a new path are recorded too. It reads the same patch format +// as the Codex provider. +func patchPaths(patch, cwd string) []string { + var paths []string + for _, line := range strings.Split(patch, "\n") { + for _, prefix := range []string{"*** Add File: ", "*** Update File: ", "*** Delete File: ", "*** Move to: "} { + path, ok := strings.CutPrefix(strings.TrimRight(line, "\r"), prefix) + if !ok { + continue + } + if path = absPath(strings.TrimSpace(path), cwd); path != "" && !slices.Contains(paths, path) { + paths = append(paths, path) + } + } + } + return paths } // readToolCalls maps a batch of calls to one input. File tools win over a @@ -324,18 +388,14 @@ func (p *Provider) readToolCalls(input *trace.HookInput, raw hookPayload) { if input.ToolName == "" { input.ToolName = call.Name } - if path := absPath(decodeToolArgs(call.Args).Path, input.Cwd); path != "" && !slices.Contains(paths, path) { - paths = append(paths, path) + for _, path := range toolPaths(call.Name, call.Args, input.Cwd) { + if !slices.Contains(paths, path) { + paths = append(paths, path) + } } } - switch { - case len(paths) == 1: - input.FilePath = paths[0] - return - case len(paths) > 1: - input.FilePaths = paths - return - case input.ToolName != "": + if input.ToolName != "" { + setPaths(input, paths) return } diff --git a/app/cli/internal/trace/copilot/hooks_test.go b/app/cli/internal/trace/copilot/hooks_test.go index 4d11e396f..ead64953a 100644 --- a/app/cli/internal/trace/copilot/hooks_test.go +++ b/app/cli/internal/trace/copilot/hooks_test.go @@ -217,6 +217,19 @@ func TestReadHookInput(t *testing.T) { payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCalls":[{"id":"t1","name":"report_intent","args":"{}"},{"id":"t2","name":"bash","args":"{\"command\":\"go test\"}"}]}`, want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolBash, Command: "go test"}, }, + { + name: "post tool, apply_patch with the patch as a string", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCallId":"c1","toolName":"apply_patch","toolArgs":"*** Begin Patch\n*** Add File: /work/repo/greeting.txt\n+hello\n*** End Patch\n"}`, + want: trace.HookInput{SessionID: testHookSession, Cwd: cwd, ToolName: toolApplyPatch, FilePath: "/work/repo/greeting.txt"}, + }, + { + name: "pre tool, batched apply_patch over several files and a move", + payload: `{"sessionId":"s-1","cwd":"/work/repo","toolCalls":[{"id":"c1","name":"apply_patch","args":"*** Begin Patch\n*** Update File: src/a.go\n@@\n-a\n+b\n*** Delete File: old.txt\n*** Update File: b.go\n*** Move to: c.go\n*** End Patch\n"}]}`, + want: trace.HookInput{ + SessionID: testHookSession, Cwd: cwd, ToolName: toolApplyPatch, + FilePaths: []string{"/work/repo/src/a.go", "/work/repo/old.txt", "/work/repo/b.go", "/work/repo/c.go"}, + }, + }, { name: "other tool", payload: `{"sessionId":"s-1","cwd":"/work/repo","toolName":"view","toolArgs":{"path":"/work/repo/a.md"}}`, @@ -245,7 +258,7 @@ func TestReadHookInput(t *testing.T) { func TestToolLists(t *testing.T) { p := New() - for _, tool := range []string{toolCreate, "edit"} { + for _, tool := range []string{toolCreate, "edit", toolApplyPatch} { assert.True(t, p.IsFileWritingTool(tool), tool) assert.False(t, p.IsCommandTool(tool), tool) } diff --git a/app/cli/internal/trace/copilot/parse.go b/app/cli/internal/trace/copilot/parse.go index 7c4bd1db9..8ab822a24 100644 --- a/app/cli/internal/trace/copilot/parse.go +++ b/app/cli/internal/trace/copilot/parse.go @@ -99,6 +99,7 @@ type logEvent struct { type eventData struct { SessionID string `json:"sessionId"` CopilotVersion string `json:"copilotVersion"` + SelectedModel string `json:"selectedModel"` NewModel string `json:"newModel"` Model string `json:"model"` Content string `json:"content"` @@ -249,6 +250,7 @@ func (p *logParser) consume(e logEvent, data eventData, line int) error { if data.CopilotVersion != "" { p.data.Agent.Version = data.CopilotVersion } + p.noteModel(data.SelectedModel) case eventModelChange: p.noteModel(data.NewModel) case eventUserMessage: @@ -268,6 +270,8 @@ func (p *logParser) consume(e logEvent, data eventData, line int) error { } func (p *logParser) consumeAssistantMessage(e logEvent, data eventData) { + // Newer Copilot releases name the model on each message. + p.noteModel(data.Model) if e.AgentID == "" { p.data.Conversation.AssistantMessages++ } @@ -428,6 +432,18 @@ func (p *logParser) finish() error { return nil } +// toolInput returns the arguments of a tool call as a JSON object, which the +// session viewer expects. Arguments that are not an object, such as the +// patch text of apply_patch, go in an input field, as for Codex. +func toolInput(args json.RawMessage) json.RawMessage { + var object map[string]json.RawMessage + if len(args) == 0 || (json.Unmarshal(args, &object) == nil && object != nil) { + return args + } + wrapped, _ := json.Marshal(map[string]json.RawMessage{"input": args}) + return wrapped +} + // rawEntry converts the messages and tool results to the shared line shape, // so the session viewer can show them, and keeps the native event in // source_event. Other events stay as Copilot wrote them. @@ -455,7 +471,7 @@ func rawEntry(e logEvent, data eventData, raw json.RawMessage, line int) json.Ra blocks = append(blocks, trace.RawSessionTextBlock{Type: "text", Text: data.Content}) } for _, req := range data.ToolRequests { - blocks = append(blocks, trace.RawSessionToolUseBlock{Type: "tool_use", ID: req.ToolCallID, Name: req.Name, Input: req.Arguments}) + blocks = append(blocks, trace.RawSessionToolUseBlock{Type: "tool_use", ID: req.ToolCallID, Name: req.Name, Input: toolInput(req.Arguments)}) } case eventToolComplete: entry.Type = trace.RoleUser diff --git a/app/cli/internal/trace/copilot/parse_test.go b/app/cli/internal/trace/copilot/parse_test.go index 7659ea2fd..7de9a9842 100644 --- a/app/cli/internal/trace/copilot/parse_test.go +++ b/app/cli/internal/trace/copilot/parse_test.go @@ -154,6 +154,12 @@ func TestParseSessionUsageSources(t *testing.T) { {"type":"assistant.message","data":{"content":"hi","outputTokens":7}}`, wantOutput: 7, wantWarning: "only the output tokens", wantPrimary: testModel, }, + { + name: "model from each message", + events: `{"type":"assistant.message","data":{"model":"gpt-6.1-sol","content":"a","outputTokens":3}} +{"type":"assistant.message","data":{"model":"gpt-6.1-sol","content":"b","outputTokens":4}}`, + wantOutput: 7, wantWarning: "only the output tokens", wantPrimary: "gpt-6.1-sol", + }, { name: "no usage", events: `{"type":"user.message","data":{"content":"hi"}}`, @@ -206,6 +212,21 @@ func TestParseSessionErrors(t *testing.T) { }) } +func TestToolInput(t *testing.T) { + cases := []struct { + name, args, want string + }{ + {name: "object stays", args: `{"path":"a"}`, want: `{"path":"a"}`}, + {name: "patch string is wrapped", args: `"*** Begin Patch"`, want: `{"input":"*** Begin Patch"}`}, + {name: "null is wrapped", args: `null`, want: `{"input":null}`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.JSONEq(t, tc.want, string(toolInput(json.RawMessage(tc.args)))) + }) + } +} + func TestEstimateCost(t *testing.T) { u := tokenUsage{Input: 1_000_000, Output: 1_000_000, CacheRead: 1_000_000} cases := []struct { diff --git a/app/cli/internal/trace/e2e/config.yaml b/app/cli/internal/trace/e2e/config.yaml index 5c1b335e7..4ca63a47e 100644 --- a/app/cli/internal/trace/e2e/config.yaml +++ b/app/cli/internal/trace/e2e/config.yaml @@ -35,13 +35,17 @@ harnesses: models: - openrouter/openai/gpt-6-luna # Copilot CLI runs with COPILOT_HOME next to the workspace, so it has no - # stored login: it needs a token with Copilot access in - # COPILOT_GITHUB_TOKEN, GH_TOKEN or GITHUB_TOKEN. The Copilot agent in VS - # Code has no headless mode, so the suite does not run it. + # stored login. It needs either 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 (for example an Azure OpenAI + # deployment: COPILOT_PROVIDER_TYPE=azure, COPILOT_PROVIDER_BASE_URL, + # COPILOT_PROVIDER_API_KEY, COPILOT_PROVIDER_WIRE_API=responses). The pinned + # model runs on such a provider. The Copilot agent in VS Code has no + # headless mode, so the suite does not run it. Copilot: - version: "1.0.82" + version: "1.0.109" models: - - claude-haiku-4.5 + - gpt-6.1-sol # Runs and pass threshold of a cell whose feature depends on the model # following an instruction (R-006, D-004). A cell of any other feature runs diff --git a/app/cli/internal/trace/e2e/copilot.go b/app/cli/internal/trace/e2e/copilot.go index efb58e561..34d8cfd0c 100644 --- a/app/cli/internal/trace/e2e/copilot.go +++ b/app/cli/internal/trace/e2e/copilot.go @@ -82,8 +82,9 @@ func parseCopilotVersion(out []byte) (string, error) { return "", errors.New("copilot --version: no version in the output") } -// Run implements Harness. It runs `copilot -p` and approves all tools, -// because a headless run cannot answer a permission question. +// Run implements Harness. It runs `copilot -p`, trusts the workspace, and +// approves all tools, because a headless run cannot answer a trust or +// permission question. // // COPILOT_HOME is a folder next to the workspace, so the configuration, the // user hooks and the sessions of the user who runs the suite do not load or @@ -106,6 +107,10 @@ func (c *Copilot) Run(ctx context.Context, req RunRequest) (*RunOutput, error) { args := []string{ "-p", req.Prompt, + // Copilot loads the repository hooks (.github/hooks) only for a + // trusted folder. The isolated COPILOT_HOME trusts no folder, so the + // run trusts the workspace for this one session. + "--trust-folder", "--allow-all-tools", "--no-ask-user", flagModel, req.Model, From be2c5b75e6a3f8710ce814e8f052e4c3d31a2ede Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 01:36:59 +0100 Subject: [PATCH 06/16] fix(trace): address review comments on the Copilot provider Reject a non-regular Copilot log before opening it, so a FIFO cannot block the hook, and report a read error of the first line. Add a command-tree test for the copilot hook subcommands. Document the mixed pre-tool batch limit (#3803). Spec: describe the payload forms by event name, narrow R-007 to the model channel, list every requirement that the VS Code fallback affects, and add Windows as a Non-Goal (#3802). Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/cmd/trace_hook_test.go | 12 +++++++++++ app/cli/internal/trace/README.md | 1 + app/cli/internal/trace/copilot/copy.go | 20 +++++++++++++------ .../internal/trace/copilot/provider_test.go | 18 +++++++++++++++++ .../issue-3800-copilot-trace-provider.md | 7 ++++--- 5 files changed, 49 insertions(+), 9 deletions(-) diff --git a/app/cli/cmd/trace_hook_test.go b/app/cli/cmd/trace_hook_test.go index a4d9b77c2..91bd23be2 100644 --- a/app/cli/cmd/trace_hook_test.go +++ b/app/cli/cmd/trace_hook_test.go @@ -36,6 +36,18 @@ func TestTraceHookPiCommands(t *testing.T) { } } +// TestTraceHookCopilotCommands pins the subcommand names that the Copilot hook +// file calls, so a renamed command cannot break recording without notice. +func TestTraceHookCopilotCommands(t *testing.T) { + root := newTraceHookCmd() + for _, name := range []string{"session-start", "pre-tool-use", "post-tool-use", "session-end"} { + command, args, err := root.Find([]string{"copilot", name}) + require.NoError(t, err) + assert.Equal(t, name, command.Name()) + assert.Empty(t, args) + } +} + func TestApplyPrePushPolicy(t *testing.T) { failure := errors.New("setup failed") prePush := newTraceHookGitPrePushCmd() diff --git a/app/cli/internal/trace/README.md b/app/cli/internal/trace/README.md index edc5c9f65..95d16eb4d 100644 --- a/app/cli/internal/trace/README.md +++ b/app/cli/internal/trace/README.md @@ -103,6 +103,7 @@ Why not Yes: - **Net contribution and line ranges, all agents:** the push finds the last writer of each line with `git blame`. A later commit that only re-indents a line takes the line, because blame sees a change. For Cursor, the limits of line attribution apply too. - **Session updates, all agents:** the update works only in the clone where the work happened, while the CLI keeps the trace state of the session (30 days), and only when the commits of the session are on the branch that the push sends. The push reads only the commits that are not on the default branch of the remote (`origin/HEAD`, or else `origin/main` or `origin/master`). After the commits of a session are pushed to that branch, a later commit does not update the session. - **Renames and rewrites, all agents:** this works only in the clone where the work happened. Git finds a rename only when the file keeps at least half of its content. Two pushed commits can rename a file one after the other. A later change to the file under its middle name does not send the session again. A rename inside an amend or a squash of the session commit loses the AI lines: the new commit creates the file under its new name, so no line of it matches the trace state (issue 3686). The limits of session updates apply too. For Cursor, the limits of line attribution apply too. +- **Shell changes attribution, Copilot:** Copilot CLI sends the pre-tool hook as a batch of calls. When one batch holds both a file tool and a shell tool, the provider snapshots only the files, so the changes of the shell command are not attributed. Real sessions did not show such a batch ([#3803](https://github.com/chainloop-dev/chainloop/issues/3803)). - **Shell changes attribution, all agents:** the hook before a shell command records only a hash of each file, not its content. The command's changes are the commits that it wrote itself, each against the `HEAD` it replaced, plus the worktree against the `HEAD` after the command. The `HEAD` reflog tells the command's own commits apart from moves to commits that it did not write, such as a rebase, a pull, a merge, a checkout or a reset: lines that such a move brings in do not count (PFM-8131). Both the files and the reftable ref storage are read. When the reflog is off, rewritten, or does not lead from the old `HEAD` to the new one, no commit of the command counts. Uncommitted lines that an earlier agent edit recorded are not recorded again, but uncommitted human lines of a file that the command changes count as AI. ## User experience diff --git a/app/cli/internal/trace/copilot/copy.go b/app/cli/internal/trace/copilot/copy.go index 710ef9b57..9d04d13d6 100644 --- a/app/cli/internal/trace/copilot/copy.go +++ b/app/cli/internal/trace/copilot/copy.go @@ -81,26 +81,34 @@ func (p *Provider) CopySessionData(store *state.Store, loc trace.SessionLocation return err } - src, err := os.Open(resolved) + // Check the file type before the open: opening a FIFO blocks. + info, err := os.Stat(resolved) if errors.Is(err, os.ErrNotExist) { return nil } if err != nil { return err } - defer src.Close() - info, err := src.Stat() - if err != nil { - return err - } if !info.Mode().IsRegular() { return errors.New("copy Copilot session: transcript is not a regular file") } + src, err := os.Open(resolved) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + defer src.Close() + // The session.start record, not the path, owns the session identity. scanner := bufio.NewScanner(src) scanner.Buffer(make([]byte, 64*1024), maxHookPayloadBytes) if !scanner.Scan() { + if err := scanner.Err(); err != nil { + return fmt.Errorf("copy Copilot session: read session.start: %w", err) + } // Copilot writes session.start first. An empty log is not yet a session. return nil } diff --git a/app/cli/internal/trace/copilot/provider_test.go b/app/cli/internal/trace/copilot/provider_test.go index 2de8985b1..574c20327 100644 --- a/app/cli/internal/trace/copilot/provider_test.go +++ b/app/cli/internal/trace/copilot/provider_test.go @@ -19,7 +19,9 @@ import ( "bytes" "os" "path/filepath" + "syscall" "testing" + "time" "github.com/chainloop-dev/chainloop/app/cli/internal/trace" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" @@ -138,6 +140,22 @@ func TestCopySessionData(t *testing.T) { assert.Nil(t, copied(t, store)) }) + t.Run("a FIFO at the log path is rejected without blocking", func(t *testing.T) { + root := copilotHome(t, "") + dir := filepath.Join(root, testSessionID) + require.NoError(t, os.MkdirAll(dir, 0o755)) + require.NoError(t, syscall.Mkfifo(filepath.Join(dir, eventsFile), 0o600)) + + done := make(chan error, 1) + go func() { done <- p.CopySessionData(newStore(t), trace.SessionLocation{SessionID: testSessionID}) }() + select { + case err := <-done: + require.Error(t, err) + case <-time.After(5 * time.Second): + require.FailNow(t, "CopySessionData blocked on a FIFO") + } + }) + t.Run("invalid session ID", func(t *testing.T) { require.Error(t, p.CopySessionData(newStore(t), trace.SessionLocation{SessionID: "../x"})) }) diff --git a/docs/specs/issue-3800-copilot-trace-provider.md b/docs/specs/issue-3800-copilot-trace-provider.md index ee3bea54b..aeb8a3066 100644 --- a/docs/specs/issue-3800-copilot-trace-provider.md +++ b/docs/specs/issue-3800-copilot-trace-provider.md @@ -41,6 +41,7 @@ Chainloop Trace supports developers who use GitHub Copilot as their coding agent - Non-goal: Support the older VS Code agent that GitHub calls the "Local" harness. It has a different hook parser and different transcript storage. Follow-up: a new ticket, if users ask for it. - Non-goal: Trace sessions of the Copilot cloud coding agent. It runs in GitHub Actions, not on the computer of the developer, and no developer push follows it. - Non-goal: Record subagents as separate entries in the evidence. Copilot writes no separate child transcripts. The hooks still attribute the edits of a subagent. Follow-up: a new ticket. +- Non-goal: Record Copilot sessions on Windows. The hook file has POSIX shell commands only, as for Claude Code and Cursor. Follow-up: [#3802](https://github.com/chainloop-dev/chainloop/issues/3802). - Non-goal: Change the evidence schema, the control-plane APIs, or the default provider. ## Requirements @@ -71,7 +72,7 @@ Trace MUST parse its private copy of the session transcript. Copying MUST check ### R-007: Session instructions -Trace MUST send the spec capture instructions at session start. After a push, Trace MUST show the session link through the post-tool channel. Each hook response MUST be one JSON document at most, and an empty message MUST produce no output. +Trace MUST send the spec capture instructions at session start. After a push, Trace MUST give the session link to the model through the post-tool channel, so that the model tells the user. Each hook response MUST be one JSON document at most, and an empty message MUST produce no output. ### R-008: Skills used during the session @@ -96,7 +97,7 @@ The end-to-end suite MUST have a Copilot column, run with Copilot CLI. A person The developer runs Trace initialization and selects Copilot. Trace writes its own hook file into the repository hook folder of Copilot. The developer then works in Copilot CLI or in VS Code. Copilot sends session, prompt, tool, and stop events to the Trace hooks. -Each hook detects the payload form. Copilot CLI sends camel-case fields. The VS Code form adds an event name and snake-case fields. It has one stop event for the end of a turn and for the end of a session. Trace maps both forms to the same session lifecycle. It snapshots files before the file tools, and snapshots the working tree around shell commands. +The event name in a hook file selects the payload form. Trace registers the camel-case event names, so Copilot CLI and VS Code send camel-case fields to the Trace hooks. The hooks that Copilot runs from the Claude Code settings get the VS Code compatible form, with snake-case fields and Pascal-case event names. Trace accepts both forms, and maps them to the same session lifecycle. It snapshots files before the file tools, and snapshots the working tree around shell commands. Copilot keeps each session as a JSON Lines event log in its user folder. Trace copies the log into private storage at session boundaries and again before evidence assembly. Copilot writes the token totals after the last hook returns, so the copy at push time holds them. The parser keeps the native records, and derives the conversation, tools, models, and token usage. @@ -134,7 +135,7 @@ Trace writes its own file in the Copilot hook folder. Each hook in it carries th ## Open Questions -- [ ] **Does the Copilot agent in VS Code write the same session event log as Copilot CLI?** Proposed: yes. GitHub says that the hosts share the agent and its hooks. Milestone 1 checks this. If the log is different, VS Code sessions keep their hooks and attribution. Trace then gives a warning about the transcript, and a follow-up ticket adds a parser. This fallback supersedes the VS Code part of R-004 and changes the first goal. +- [ ] **Does the Copilot agent in VS Code write the same session event log as Copilot CLI?** Proposed: yes. GitHub says that the hosts share the agent and its hooks. Milestone 1 checks this. If the log is different, VS Code sessions keep their hooks and attribution. Trace then gives a warning about the transcript, and a follow-up ticket adds a parser. This fallback supersedes the VS Code parts of R-001, R-004, R-006, R-008, and R-009, and changes the first goal. ## Milestones From f90d7b5ffc0add3227fd3ab1a0a3b96fabe515a5 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 01:38:25 +0100 Subject: [PATCH 07/16] fix(trace): give Copilot tool calls without arguments an empty input Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/internal/trace/copilot/parse.go | 5 ++++- app/cli/internal/trace/copilot/parse_test.go | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/app/cli/internal/trace/copilot/parse.go b/app/cli/internal/trace/copilot/parse.go index 8ab822a24..d6ab58afc 100644 --- a/app/cli/internal/trace/copilot/parse.go +++ b/app/cli/internal/trace/copilot/parse.go @@ -436,8 +436,11 @@ func (p *logParser) finish() error { // session viewer expects. Arguments that are not an object, such as the // patch text of apply_patch, go in an input field, as for Codex. func toolInput(args json.RawMessage) json.RawMessage { + if len(args) == 0 { + return json.RawMessage(`{}`) + } var object map[string]json.RawMessage - if len(args) == 0 || (json.Unmarshal(args, &object) == nil && object != nil) { + if json.Unmarshal(args, &object) == nil && object != nil { return args } wrapped, _ := json.Marshal(map[string]json.RawMessage{"input": args}) diff --git a/app/cli/internal/trace/copilot/parse_test.go b/app/cli/internal/trace/copilot/parse_test.go index 7de9a9842..9bfdb647b 100644 --- a/app/cli/internal/trace/copilot/parse_test.go +++ b/app/cli/internal/trace/copilot/parse_test.go @@ -219,6 +219,7 @@ func TestToolInput(t *testing.T) { {name: "object stays", args: `{"path":"a"}`, want: `{"path":"a"}`}, {name: "patch string is wrapped", args: `"*** Begin Patch"`, want: `{"input":"*** Begin Patch"}`}, {name: "null is wrapped", args: `null`, want: `{"input":null}`}, + {name: "no arguments give an empty object", args: ``, want: `{}`}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { From c4463ef14b805f1f2385cec132d29724410f00af Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 01:53:00 +0100 Subject: [PATCH 08/16] feat(trace): show the Copilot start banner and session link to the user Copilot shows the progress messages of a hook to the user. The Copilot provider now writes the session-start banner and the session link after a push as progress lines, before the additionalContext for the model. Checked by hand with Copilot CLI 1.0.109. Spec: R-007 now requires the banner and the session link for the user. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/internal/trace/README.md | 7 ++- app/cli/internal/trace/copilot/provider.go | 47 +++++++++++++------ .../internal/trace/copilot/provider_test.go | 30 ++++++++++-- .../trace/providers/capabilities_test.go | 2 +- .../issue-3800-copilot-trace-provider.md | 2 +- 5 files changed, 62 insertions(+), 26 deletions(-) diff --git a/app/cli/internal/trace/README.md b/app/cli/internal/trace/README.md index 95d16eb4d..b4fb6842b 100644 --- a/app/cli/internal/trace/README.md +++ b/app/cli/internal/trace/README.md @@ -32,7 +32,7 @@ GitHub Copilot uses one provider for Copilot CLI and the Copilot agent in VS Cod 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 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 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. ## Setup @@ -114,7 +114,7 @@ The Codex welcome message and session link after push were verified manually in | Feature | What it means | Claude Code | Cursor | OpenCode 1.x | OpenCode 2 | Pi | Codex | Copilot | |---------|---------------|-------------|--------|--------------|------------|---|---|---| -| Welcome message | At session start, the user sees a message that tells that Chainloop records the session, and where the evidence goes: the Chainloop project, or the on-disk path in local mode (spec issue-3582). | Yes | No | No | No | Unknown | Yes | No | +| Welcome message | At session start, the user sees a message that tells that Chainloop records the session, and where the evidence goes: the Chainloop project, or the on-disk path in local mode (spec issue-3582). | Yes | No | No | No | Unknown | Yes | Yes | | Session link after push | After a `git push` that the agent runs, the user sees a link to the session in Chainloop. | Yes | No | No | No | Unknown | Yes | Unknown | | Credentials warning | At session start, in control-plane mode, the user is told when the control plane does not accept the CLI credentials (for example, an expired token), so the push will not upload the session. The hook uses the same check as `chainloop trace init`. An unreachable control plane, or a check that takes more than 2 seconds, shows no warning. | Yes | Partial | Partial | Partial | Unknown | Unknown | Unknown | @@ -126,8 +126,7 @@ Why not Yes: - **Welcome message, Cursor and OpenCode:** the provider gives the session-start context to the model only. It has no channel that shows a message to the user at session start, so the welcome message is dropped. - **Credentials warning, Cursor and OpenCode:** the provider has no channel to the user at session start. The model is told to tell the user, so the warning depends on the model. - **Session link after push, Cursor:** the `postToolUse` hook runs after a shell command, but its response has no field that Cursor shows to the user. The link stays pending until it expires. -- **Welcome message, Copilot:** Copilot documents no session-start output that it shows to the user. The provider gives the session-start context to the model only. -- **Session link after push and credentials warning, Copilot:** not verified yet. The link goes in the `additionalContext` of the `postToolUse` response, which the model reads. The credentials warning goes in the session-start instruction, so it depends on the model. +- **Session link after push and credentials warning, Copilot:** these need a control plane, so the end-to-end suite does not cover them. The link and the warning go to the user as hook progress lines, the same channel as the welcome message, and the link also goes to the model in `additionalContext`. - **Session link after push, OpenCode:** the plugin hook fires after a shell command, but the response that shows a message to the user is not verified yet. The link stays pending until it expires. ## Specs and skills diff --git a/app/cli/internal/trace/copilot/provider.go b/app/cli/internal/trace/copilot/provider.go index 2fe57fcda..f21c2016b 100644 --- a/app/cli/internal/trace/copilot/provider.go +++ b/app/cli/internal/trace/copilot/provider.go @@ -102,9 +102,9 @@ func (p *Provider) IsCommandTool(toolName string) bool { return slices.Contains(commandTools, toolName) } -// SupportsSessionStartBanner is false: Copilot documents no session-start -// output that it shows to the user. -func (p *Provider) SupportsSessionStartBanner() bool { return false } +// SupportsSessionStartBanner is true: Copilot shows the progress messages of a +// hook to the user. +func (p *Provider) SupportsSessionStartBanner() bool { return true } // SupportsSessionStartInstruction is true: Copilot adds the additionalContext // of a sessionStart hook to the session. @@ -114,36 +114,53 @@ func (p *Provider) SupportsSessionStartInstruction() bool { return true } // userPromptSubmitted command hook. func (p *Provider) SupportsPromptReminder() bool { return false } -// AnnounceSessionStart gives the instruction to the model. +// AnnounceSessionStart shows the banner to the user and gives the +// instruction to the model. func (p *Provider) AnnounceSessionStart(msg trace.SessionStartMessage) error { - return p.writeContext(msg.Instruction) + return p.writeResponse(msg.Banner, msg.Instruction) } // AnnouncePromptSubmit does nothing: Copilot drops the output of the hook. func (p *Provider) AnnouncePromptSubmit(string) error { return nil } -// AnnounceToUser adds the message to the result of the tool, so the model -// sees it in the same turn and tells the user. +// AnnounceToUser shows the message to the user, and adds it to the result of +// the tool, so that the model can repeat it in the same turn. func (p *Provider) AnnounceToUser(msg string) error { if msg == "" { return nil } - return p.writeContext("Tell the user the following, including any link verbatim: " + msg) + return p.writeResponse(msg, "Tell the user the following, including any link verbatim: "+msg) } -// hookResponse is the output of a sessionStart or postToolUse hook. +// progressMessage is a line that Copilot shows to the user, before the final +// output of a hook. It does not change the output. +type progressMessage struct { + Type string `json:"type"` + Message string `json:"message"` +} + +// hookResponse is the final output of a sessionStart or postToolUse hook. type hookResponse struct { AdditionalContext string `json:"additionalContext"` } -// writeContext writes one JSON document, or nothing for an empty context. -func (p *Provider) writeContext(context string) error { - if context == "" { - return nil - } +// writeResponse writes the message for the user as a progress line, then the +// context for the model as the final JSON document. Each is one line, and an +// empty one is left out. Copilot reads only the last document as the output +// of the hook. +func (p *Provider) writeResponse(userMessage, context string) error { out := p.out if out == nil { out = os.Stdout } - return json.NewEncoder(out).Encode(hookResponse{AdditionalContext: context}) + enc := json.NewEncoder(out) + if userMessage != "" { + if err := enc.Encode(progressMessage{Type: "progress", Message: userMessage}); err != nil { + return err + } + } + if context == "" { + return nil + } + return enc.Encode(hookResponse{AdditionalContext: context}) } diff --git a/app/cli/internal/trace/copilot/provider_test.go b/app/cli/internal/trace/copilot/provider_test.go index 574c20327..dfa9bb9af 100644 --- a/app/cli/internal/trace/copilot/provider_test.go +++ b/app/cli/internal/trace/copilot/provider_test.go @@ -168,15 +168,34 @@ func TestAnnounce(t *testing.T) { want string }{ { - name: "session start instruction", + name: "session start banner and instruction", run: func(p *Provider) error { return p.AnnounceSessionStart(trace.SessionStartMessage{Banner: "banner", Instruction: "capture the spec"}) }, - want: `{"additionalContext":"capture the spec"}` + "\n", + want: `{"type":"progress","message":"banner"}` + "\n" + `{"additionalContext":"capture the spec"}` + "\n", }, { - name: "session start with no instruction", + name: "session start banner only", run: func(p *Provider) error { return p.AnnounceSessionStart(trace.SessionStartMessage{Banner: "banner"}) }, + want: `{"type":"progress","message":"banner"}` + "\n", + }, + { + name: "session start instruction only", + run: func(p *Provider) error { + return p.AnnounceSessionStart(trace.SessionStartMessage{Instruction: "capture the spec"}) + }, + want: `{"additionalContext":"capture the spec"}` + "\n", + }, + { + name: "multi-line banner stays one progress line", + run: func(p *Provider) error { + return p.AnnounceSessionStart(trace.SessionStartMessage{Banner: "line 1\nline 2"}) + }, + want: `{"type":"progress","message":"line 1\nline 2"}` + "\n", + }, + { + name: "empty session start", + run: func(p *Provider) error { return p.AnnounceSessionStart(trace.SessionStartMessage{}) }, }, { name: "prompt reminder is dropped", @@ -185,7 +204,8 @@ func TestAnnounce(t *testing.T) { { name: "announce to user", run: func(p *Provider) error { return p.AnnounceToUser("https://example.com/s") }, - want: `{"additionalContext":"Tell the user the following, including any link verbatim: https://example.com/s"}` + "\n", + want: `{"type":"progress","message":"https://example.com/s"}` + "\n" + + `{"additionalContext":"Tell the user the following, including any link verbatim: https://example.com/s"}` + "\n", }, { name: "empty announce", @@ -202,7 +222,7 @@ func TestAnnounce(t *testing.T) { } p := New() - assert.False(t, p.SupportsSessionStartBanner()) + assert.True(t, p.SupportsSessionStartBanner()) assert.True(t, p.SupportsSessionStartInstruction()) assert.False(t, p.SupportsPromptReminder()) } diff --git a/app/cli/internal/trace/providers/capabilities_test.go b/app/cli/internal/trace/providers/capabilities_test.go index ea7058a6d..4bb61f590 100644 --- a/app/cli/internal/trace/providers/capabilities_test.go +++ b/app/cli/internal/trace/providers/capabilities_test.go @@ -64,7 +64,7 @@ func TestSessionStartChannels(t *testing.T) { }, {provider: codex.Name, wantBanner: true, wantInstruction: true, wantReminder: true, why: "Codex surfaces systemMessage and supports additionalContext at session start and user prompt"}, {provider: pi.Name, wantBanner: true, wantInstruction: true, wantReminder: true, why: "Pi shows banners in its UI and injects the session instruction and prompt reminder through the project extension"}, - {provider: copilot.Name, wantBanner: false, wantInstruction: true, wantReminder: false, why: "Copilot adds the additionalContext of sessionStart to the session, documents no session-start output for the user, and drops the output of userPromptSubmitted"}, + {provider: copilot.Name, wantBanner: true, wantInstruction: true, wantReminder: false, why: "Copilot shows the progress messages of a hook to the user, adds the additionalContext of sessionStart to the session, and drops the output of userPromptSubmitted"}, } for _, tc := range testCases { diff --git a/docs/specs/issue-3800-copilot-trace-provider.md b/docs/specs/issue-3800-copilot-trace-provider.md index aeb8a3066..7fd84dab8 100644 --- a/docs/specs/issue-3800-copilot-trace-provider.md +++ b/docs/specs/issue-3800-copilot-trace-provider.md @@ -72,7 +72,7 @@ Trace MUST parse its private copy of the session transcript. Copying MUST check ### R-007: Session instructions -Trace MUST send the spec capture instructions at session start. After a push, Trace MUST give the session link to the model through the post-tool channel, so that the model tells the user. Each hook response MUST be one JSON document at most, and an empty message MUST produce no output. +At session start, Trace MUST show the user a banner that says that Trace records the session. Trace MUST also send the spec capture instructions to the model. After a push, Trace MUST show the session link to the user and give it to the model, through the post-tool channel. The message for the user MUST be a progress line, which Copilot shows to the user. Each hook response MUST have at most one output document after it, and an empty message MUST produce no output. ### R-008: Skills used during the session From f6b453dd2d1732a48673f88b5c7e28f19a8066a7 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:01:06 +0100 Subject: [PATCH 09/16] test(trace): check the Claude Code guard with real Copilot payloads Add the payloads that Copilot CLI 1.0.109 sends to the hooks of .claude/settings.json, so the guard of R-003 is tested against real shapes. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/internal/trace/claude/hooks_test.go | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/app/cli/internal/trace/claude/hooks_test.go b/app/cli/internal/trace/claude/hooks_test.go index 52dc174b0..eefc659ca 100644 --- a/app/cli/internal/trace/claude/hooks_test.go +++ b/app/cli/internal/trace/claude/hooks_test.go @@ -358,6 +358,24 @@ func TestReadHookInput(t *testing.T) { name: "snake_case form with a numeric timestamp", payload: `{"session_id":"s-1","hook_event_name":"PostToolUse","timestamp":1775596074872,"tool_name":"Bash","tool_input":{"command":"ls"}}`, }, + // The shapes below are real payloads of Copilot CLI 1.0.109, captured + // from the hooks of .claude/settings.json, with the paths shortened. + { + name: "Copilot CLI session start", + payload: `{"hook_event_name":"SessionStart","session_id":"9869f5f4-d4a3-4049-a047-94714272d2d0","timestamp":"2026-11-11T01:00:08.528Z","cwd":"/repo","source":"new","initial_prompt":"Create a file"}`, + }, + { + name: "Copilot CLI prompt", + payload: `{"hook_event_name":"UserPromptSubmit","session_id":"9869f5f4-d4a3-4049-a047-94714272d2d0","timestamp":"2026-11-11T01:00:08.548Z","cwd":"/repo","prompt":"Create a file"}`, + }, + { + name: "Copilot CLI shell tool", + payload: `{"hook_event_name":"PreToolUse","session_id":"9869f5f4-d4a3-4049-a047-94714272d2d0","timestamp":"2026-11-11T01:00:16.243Z","cwd":"/repo","tool_use_id":"call_1","tool_name":"Bash","tool_input":{"command":"cat a.txt","description":"Print a.txt"}}`, + }, + { + name: "Copilot CLI session end", + payload: `{"hook_event_name":"SessionEnd","session_id":"9869f5f4-d4a3-4049-a047-94714272d2d0","timestamp":"2026-11-11T01:00:18.446Z","cwd":"/repo","reason":"complete"}`, + }, { name: "camelCase session ID", payload: `{"sessionId":"s-1","session_id":"s-1","hook_event_name":"SessionStart"}`, @@ -377,6 +395,16 @@ func TestReadHookInput(t *testing.T) { }) } + t.Run("records nothing for a Copilot patch edit", func(t *testing.T) { + // Copilot names apply_patch Edit and sends the patch text as the tool + // input, which the Claude Code payload cannot hold. + r := bytes.NewBufferString(`{"hook_event_name":"PreToolUse","session_id":"9869f5f4-d4a3-4049-a047-94714272d2d0","timestamp":"2026-11-11T01:00:12.362Z","cwd":"/repo","tool_use_id":"custom_call_1","tool_name":"Edit","tool_input":"*** Begin Patch\n*** Add File: a.txt\n+hi\n*** End Patch\n"}`) + input, err := provider.ReadHookInput(r) + if err == nil { + assert.Empty(t, input.SessionID) + } + }) + t.Run("keeps a Claude Code payload with a timestamp", func(t *testing.T) { r := bytes.NewBufferString(`{"session_id":"s-1","hook_event_name":"PreToolUse","timestamp":"2026-04-08T15:04:05.000Z","transcript_path":"/home/u/.claude/projects/-repo/s-1.jsonl","tool_name":"Write","tool_input":{"file_path":"/repo/README.md"}}`) input, err := provider.ReadHookInput(r) From 79c1c832dd5f512ca6e94077ef34c1f3ffc2c3a9 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:11:53 +0100 Subject: [PATCH 10/16] chore(trace): drop the Copilot note from trace init The README covers the Copilot setup, so trace init prints no extra note for Copilot. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/cmd/trace_init.go | 3 --- app/cli/cmd/trace_init_test.go | 3 --- 2 files changed, 6 deletions(-) diff --git a/app/cli/cmd/trace_init.go b/app/cli/cmd/trace_init.go index df91b4fd6..889da4da8 100644 --- a/app/cli/cmd/trace_init.go +++ b/app/cli/cmd/trace_init.go @@ -29,7 +29,6 @@ import ( "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/config" - "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" tracegit "github.com/chainloop-dev/chainloop/app/cli/internal/trace/git" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/hooks" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" @@ -397,8 +396,6 @@ func writeTraceHarnessNotes(w io.Writer, installed []trace.Provider) { switch p.Name() { case codex.Name: fmt.Fprintln(w, "For Codex, review and trust the installed hooks in Codex before starting work.") - case copilot.Name: - fmt.Fprintln(w, "For Copilot, the hooks are in .github/hooks/chainloop-trace.json. Copilot CLI and the Copilot agent in VS Code both read it. Copilot CLI loads it only in a trusted folder: trust the repository when Copilot asks, or use --trust-folder for a prompt-mode run.") case pi.Name: fmt.Fprintln(w, "For Pi, review the project extension at .pi/extensions/chainloop-trace.ts before starting work. Interactive Pi asks to trust project files. Non-interactive runs need saved trust or --approve.") } diff --git a/app/cli/cmd/trace_init_test.go b/app/cli/cmd/trace_init_test.go index 3632b8f7d..37ef3ec7e 100644 --- a/app/cli/cmd/trace_init_test.go +++ b/app/cli/cmd/trace_init_test.go @@ -357,9 +357,6 @@ func TestWriteTraceNextSteps(t *testing.T) { if slices.Contains(tc.providers, pi.Name) { assert.Contains(t, got, "--approve") } - if slices.Contains(tc.providers, copilot.Name) { - assert.Contains(t, got, "For Copilot") - } }) } } From 5b93361d6128ea5f8546ee2409717685a6664653 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:14:18 +0100 Subject: [PATCH 11/16] chore(trace): drop the per-agent notes from the trace init summary The trace init summary now ends with the docs link. The Pi and Codex trust notes are removed, and the Trace README keeps those setup steps. This goes against Codex spec issue-3657 R-006, which is frozen, and supersedes Pi spec issue-3520 R-009 with R-010. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/cmd/trace_init.go | 15 --------------- app/cli/cmd/trace_init_local_test.go | 2 +- app/cli/cmd/trace_init_test.go | 6 +++--- docs/specs/issue-3520-pi-trace-provider.md | 12 ++++++++++-- 4 files changed, 14 insertions(+), 21 deletions(-) diff --git a/app/cli/cmd/trace_init.go b/app/cli/cmd/trace_init.go index 889da4da8..7937bb0e6 100644 --- a/app/cli/cmd/trace_init.go +++ b/app/cli/cmd/trace_init.go @@ -27,11 +27,9 @@ import ( "github.com/chainloop-dev/chainloop/app/cli/internal/repositoryconfig" "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/config" tracegit "github.com/chainloop-dev/chainloop/app/cli/internal/trace/git" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/hooks" - "github.com/chainloop-dev/chainloop/app/cli/internal/trace/pi" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/providers" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/state" "github.com/chainloop-dev/chainloop/app/cli/pkg/action" @@ -388,18 +386,6 @@ What's next Learn more: %s `, strings.Join(files, " "), joinWithOr(providerNames(installed)), traceDocsURL) - writeTraceHarnessNotes(w, installed) -} - -func writeTraceHarnessNotes(w io.Writer, installed []trace.Provider) { - for _, p := range installed { - switch p.Name() { - case codex.Name: - fmt.Fprintln(w, "For Codex, review and trust the installed hooks in Codex before starting work.") - case pi.Name: - fmt.Fprintln(w, "For Pi, review the project extension at .pi/extensions/chainloop-trace.ts before starting work. Interactive Pi asks to trust project files. Non-interactive runs need saved trust or --approve.") - } - } } // writeTraceInitLocalSummary reports what a local init set up. It names no @@ -457,7 +443,6 @@ What's next Learn more: %s `, strings.Join(files, " "), joinWithOr(providerNames(installed)), traceDocsURL) - writeTraceHarnessNotes(w, installed) } // providerNames names the harnesses, in the order they were installed. diff --git a/app/cli/cmd/trace_init_local_test.go b/app/cli/cmd/trace_init_local_test.go index e6eb9634e..c79729a73 100644 --- a/app/cli/cmd/trace_init_local_test.go +++ b/app/cli/cmd/trace_init_local_test.go @@ -202,7 +202,7 @@ func TestWriteTraceLocalNextSteps(t *testing.T) { assert.Contains(t, got, chainloopYMLName) assert.Contains(t, got, claudeSettings) assert.Contains(t, got, filepath.Join(".pi", "extensions", "chainloop-trace.ts")) - assert.Contains(t, got, "--approve") + assert.NotContains(t, got, "--approve", "the summary has no per-agent notes") assert.Contains(t, got, "writes the session evidence to disk") assert.NotContains(t, got, "the push tells you where") assert.Contains(t, got, traceDocsURL) diff --git a/app/cli/cmd/trace_init_test.go b/app/cli/cmd/trace_init_test.go index 37ef3ec7e..92caa490f 100644 --- a/app/cli/cmd/trace_init_test.go +++ b/app/cli/cmd/trace_init_test.go @@ -20,6 +20,7 @@ import ( "os" "path/filepath" "slices" + "strings" "testing" "github.com/chainloop-dev/chainloop/app/cli/internal/trace/copilot" @@ -354,9 +355,8 @@ func TestWriteTraceNextSteps(t *testing.T) { assert.Contains(t, got, tc.wantHarnesses) assert.Contains(t, got, traceDocsURL) - if slices.Contains(tc.providers, pi.Name) { - assert.Contains(t, got, "--approve") - } + // The summary ends with the docs link: no per-agent notes follow. + assert.True(t, strings.HasSuffix(strings.TrimSpace(got), traceDocsURL), "nothing follows the docs link: %q", got) }) } } diff --git a/docs/specs/issue-3520-pi-trace-provider.md b/docs/specs/issue-3520-pi-trace-provider.md index 4bae10045..6d64fccc6 100644 --- a/docs/specs/issue-3520-pi-trace-provider.md +++ b/docs/specs/issue-3520-pi-trace-provider.md @@ -116,9 +116,17 @@ When `ctx.hasUI` is true, the extension MUST show the existing Trace banner and - Done when: first start, reload, resume, fork/clone, an abandoned branch containing a marker, a spec introduced or changed after the first turn, TUI/RPC messages, clean JSON/print stdout, and JSON/print stderr delivery of every pending link follow these rules. -### R-009: Compatibility and failure safety +### ~~R-009: Compatibility and failure safety~~ +Superseded by R-010. -The first supported Pi baseline MUST be version 0.80.10 with JSONL v3. Older or incompatible persisted formats MUST fail as unsupported session evidence without blocking Pi or Git push. Initialization output MUST explain Pi project trust; non-interactive Pi requires saved trust or `--approve` for the project extension to load. Chainloop MUST NOT bypass Pi's trust mechanism. +~~The first supported Pi baseline MUST be version 0.80.10 with JSONL v3. Older or incompatible persisted formats MUST fail as unsupported session evidence without blocking Pi or Git push. Initialization output MUST explain Pi project trust; non-interactive Pi requires saved trust or `--approve` for the project extension to load. Chainloop MUST NOT bypass Pi's trust mechanism.~~ + +~~The generated extension MUST execute `chainloop` directly without a shell. Every child process MUST run in `ctx.cwd`, use a 60-second timeout, and cap each captured stdout and stderr stream at 64 KiB. At timeout the extension MUST send SIGTERM, allow a five-second grace period, and send SIGKILL only if the child remains alive. Spawn errors, timeouts, non-zero exits, malformed hook responses, and extra output MUST be absorbed by the extension and MUST NOT throw from any lifecycle, `tool_call`, or `tool_result` handler. A `tool_call` handler MUST always return `undefined` and MUST never return `{ block: true }`.~~ + +### R-010: Compatibility and failure safety +Supersedes R-009. Initialization output no longer explains Pi project trust: the trace init summary prints no per-agent notes ([PR #3801](https://github.com/chainloop-dev/chainloop/pull/3801)). The Trace README keeps the Pi trust steps. + +The first supported Pi baseline MUST be version 0.80.10 with JSONL v3. Older or incompatible persisted formats MUST fail as unsupported session evidence without blocking Pi or Git push. Non-interactive Pi requires saved trust or `--approve` for the project extension to load. Chainloop MUST NOT bypass Pi's trust mechanism. The generated extension MUST execute `chainloop` directly without a shell. Every child process MUST run in `ctx.cwd`, use a 60-second timeout, and cap each captured stdout and stderr stream at 64 KiB. At timeout the extension MUST send SIGTERM, allow a five-second grace period, and send SIGKILL only if the child remains alive. Spawn errors, timeouts, non-zero exits, malformed hook responses, and extra output MUST be absorbed by the extension and MUST NOT throw from any lifecycle, `tool_call`, or `tool_result` handler. A `tool_call` handler MUST always return `undefined` and MUST never return `{ block: true }`. From 215cbca491cbd2400410b67e6e8250482eebea35 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:17:04 +0100 Subject: [PATCH 12/16] docs: add random date to CLI readme Assisted-by: GitHub Copilot Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 386938e5-0467-469a-81ef-4aae40023df7 --- app/cli/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/cli/README.md b/app/cli/README.md index e89f6b777..ca7eef91a 100644 --- a/app/cli/README.md +++ b/app/cli/README.md @@ -1,3 +1,5 @@ +Random date: 2024-07-19 + # Command Line Interface (CLI) This Command Line Interface (CLI) is a local client that's used for two purposes: From 4fac0a5dbb20eaee06ef3e74b4f05332a9b547f1 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:17:43 +0100 Subject: [PATCH 13/16] fix(trace): skip Copilot patch payloads in the Claude Code hook without an error Copilot sends the patch text of its edit tool as a string tool_input to the hooks of .claude/settings.json. The Claude Code reader failed to decode it before the Copilot check ran, which logged a bad-input error. It now decodes tool_input after the checks for other agents. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/internal/trace/claude/hooks.go | 23 ++++++++++++++------- app/cli/internal/trace/claude/hooks_test.go | 13 +++++++++--- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/app/cli/internal/trace/claude/hooks.go b/app/cli/internal/trace/claude/hooks.go index c1c9c151e..6d0af31e4 100644 --- a/app/cli/internal/trace/claude/hooks.go +++ b/app/cli/internal/trace/claude/hooks.go @@ -203,11 +203,11 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { // Cursor-relayed events without a second pass. var raw struct { trace.HookInput - ToolInput struct { - FilePath string `json:"file_path"` - Command string `json:"command"` - } `json:"tool_input"` - CursorVersion string `json:"cursor_version"` + // ToolInput is decoded after the checks for other agents below: the + // GitHub Copilot agent sends the patch text of its edit tool as a + // string here. + ToolInput json.RawMessage `json:"tool_input"` + CursorVersion string `json:"cursor_version"` // Timestamp and SessionIDCamel are in the payloads of the GitHub // Copilot agent, which also runs these hooks. Claude Code sends // neither. @@ -235,11 +235,18 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { return &trace.HookInput{}, nil } + // A tool input that is not an object has no file path and no command. + var toolInput struct { + FilePath string `json:"file_path"` + Command string `json:"command"` + } + _ = json.Unmarshal(raw.ToolInput, &toolInput) + input := raw.HookInput - if raw.ToolInput.FilePath != "" { - input.FilePath = raw.ToolInput.FilePath + if toolInput.FilePath != "" { + input.FilePath = toolInput.FilePath } - input.Command = raw.ToolInput.Command + input.Command = toolInput.Command input.ToolFailed = input.HookEventName == eventPostToolUseFailure return &input, nil diff --git a/app/cli/internal/trace/claude/hooks_test.go b/app/cli/internal/trace/claude/hooks_test.go index eefc659ca..8dc5a48de 100644 --- a/app/cli/internal/trace/claude/hooks_test.go +++ b/app/cli/internal/trace/claude/hooks_test.go @@ -400,9 +400,16 @@ func TestReadHookInput(t *testing.T) { // input, which the Claude Code payload cannot hold. r := bytes.NewBufferString(`{"hook_event_name":"PreToolUse","session_id":"9869f5f4-d4a3-4049-a047-94714272d2d0","timestamp":"2026-11-11T01:00:12.362Z","cwd":"/repo","tool_use_id":"custom_call_1","tool_name":"Edit","tool_input":"*** Begin Patch\n*** Add File: a.txt\n+hi\n*** End Patch\n"}`) input, err := provider.ReadHookInput(r) - if err == nil { - assert.Empty(t, input.SessionID) - } + require.NoError(t, err, "a Copilot payload is skipped quietly, not reported as bad input") + assert.Empty(t, input.SessionID) + }) + + t.Run("a tool input that is not an object gives an empty file path", func(t *testing.T) { + r := bytes.NewBufferString(`{"session_id":"s-1","hook_event_name":"PreToolUse","tool_name":"Write","tool_input":"text"}`) + input, err := provider.ReadHookInput(r) + require.NoError(t, err) + assert.Equal(t, "s-1", input.SessionID) + assert.Empty(t, input.FilePath) }) t.Run("keeps a Claude Code payload with a timestamp", func(t *testing.T) { From 5d3baf07a15b7c02dc67d6149a0f70bc99cfb7fe Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:19:16 +0100 Subject: [PATCH 14/16] fix(trace): show the Copilot session link one time The progress line already shows the session link to the user. The provider no longer gives the link to the model too, so the model does not repeat it. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/internal/trace/README.md | 2 +- app/cli/internal/trace/copilot/provider.go | 9 +++------ app/cli/internal/trace/copilot/provider_test.go | 5 +++-- docs/specs/issue-3800-copilot-trace-provider.md | 2 +- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/app/cli/internal/trace/README.md b/app/cli/internal/trace/README.md index b4fb6842b..bc3327623 100644 --- a/app/cli/internal/trace/README.md +++ b/app/cli/internal/trace/README.md @@ -126,7 +126,7 @@ Why not Yes: - **Welcome message, Cursor and OpenCode:** the provider gives the session-start context to the model only. It has no channel that shows a message to the user at session start, so the welcome message is dropped. - **Credentials warning, Cursor and OpenCode:** the provider has no channel to the user at session start. The model is told to tell the user, so the warning depends on the model. - **Session link after push, Cursor:** the `postToolUse` hook runs after a shell command, but its response has no field that Cursor shows to the user. The link stays pending until it expires. -- **Session link after push and credentials warning, Copilot:** these need a control plane, so the end-to-end suite does not cover them. The link and the warning go to the user as hook progress lines, the same channel as the welcome message, and the link also goes to the model in `additionalContext`. +- **Session link after push and credentials warning, Copilot:** these need a control plane, so the end-to-end suite does not cover them. The link and the warning go to the user as hook progress lines, the same channel as the welcome message. The link does not go to the model, so the user sees it one time. - **Session link after push, OpenCode:** the plugin hook fires after a shell command, but the response that shows a message to the user is not verified yet. The link stays pending until it expires. ## Specs and skills diff --git a/app/cli/internal/trace/copilot/provider.go b/app/cli/internal/trace/copilot/provider.go index f21c2016b..d5efddf89 100644 --- a/app/cli/internal/trace/copilot/provider.go +++ b/app/cli/internal/trace/copilot/provider.go @@ -123,13 +123,10 @@ func (p *Provider) AnnounceSessionStart(msg trace.SessionStartMessage) error { // AnnouncePromptSubmit does nothing: Copilot drops the output of the hook. func (p *Provider) AnnouncePromptSubmit(string) error { return nil } -// AnnounceToUser shows the message to the user, and adds it to the result of -// the tool, so that the model can repeat it in the same turn. +// AnnounceToUser shows the message to the user as a progress line. The model +// gets no copy: it would show the message to the user a second time. func (p *Provider) AnnounceToUser(msg string) error { - if msg == "" { - return nil - } - return p.writeResponse(msg, "Tell the user the following, including any link verbatim: "+msg) + return p.writeResponse(msg, "") } // progressMessage is a line that Copilot shows to the user, before the final diff --git a/app/cli/internal/trace/copilot/provider_test.go b/app/cli/internal/trace/copilot/provider_test.go index dfa9bb9af..936f20100 100644 --- a/app/cli/internal/trace/copilot/provider_test.go +++ b/app/cli/internal/trace/copilot/provider_test.go @@ -202,10 +202,11 @@ func TestAnnounce(t *testing.T) { run: func(p *Provider) error { return p.AnnouncePromptSubmit("reminder") }, }, { + // The progress line reaches the user. The model gets no copy, so + // that it does not show the link a second time. name: "announce to user", run: func(p *Provider) error { return p.AnnounceToUser("https://example.com/s") }, - want: `{"type":"progress","message":"https://example.com/s"}` + "\n" + - `{"additionalContext":"Tell the user the following, including any link verbatim: https://example.com/s"}` + "\n", + want: `{"type":"progress","message":"https://example.com/s"}` + "\n", }, { name: "empty announce", diff --git a/docs/specs/issue-3800-copilot-trace-provider.md b/docs/specs/issue-3800-copilot-trace-provider.md index 7fd84dab8..1f0891e3d 100644 --- a/docs/specs/issue-3800-copilot-trace-provider.md +++ b/docs/specs/issue-3800-copilot-trace-provider.md @@ -72,7 +72,7 @@ Trace MUST parse its private copy of the session transcript. Copying MUST check ### R-007: Session instructions -At session start, Trace MUST show the user a banner that says that Trace records the session. Trace MUST also send the spec capture instructions to the model. After a push, Trace MUST show the session link to the user and give it to the model, through the post-tool channel. The message for the user MUST be a progress line, which Copilot shows to the user. Each hook response MUST have at most one output document after it, and an empty message MUST produce no output. +At session start, Trace MUST show the user a banner that says that Trace records the session. Trace MUST also send the spec capture instructions to the model. After a push, Trace MUST show the session link to the user one time, through the post-tool channel. The message for the user MUST be a progress line, which Copilot shows to the user. Each hook response MUST have at most one output document after it, and an empty message MUST produce no output. ### R-008: Skills used during the session From fe4af9f3c1c153c71a0492c768a8e562381371c0 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:27:04 +0100 Subject: [PATCH 15/16] fix(trace): keep strict decoding of an object tool_input in the Claude Code hook A tool_input object with a field of the wrong type is bad input again. Only a tool_input that is not an object, such as a Copilot patch string, gives no file path. Refs #3800 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1091d5bb-f3cb-4795-997a-fabee098ff93 --- app/cli/internal/trace/claude/hooks.go | 10 ++++++++-- app/cli/internal/trace/claude/hooks_test.go | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/app/cli/internal/trace/claude/hooks.go b/app/cli/internal/trace/claude/hooks.go index 6d0af31e4..6aef55f67 100644 --- a/app/cli/internal/trace/claude/hooks.go +++ b/app/cli/internal/trace/claude/hooks.go @@ -16,6 +16,7 @@ package claude import ( + "bytes" "encoding/json" "errors" "fmt" @@ -235,12 +236,17 @@ func (p *Provider) ReadHookInput(r io.Reader) (*trace.HookInput, error) { return &trace.HookInput{}, nil } - // A tool input that is not an object has no file path and no command. + // A tool input that is not an object has no file path and no command. An + // object with fields of the wrong type is bad input. var toolInput struct { FilePath string `json:"file_path"` Command string `json:"command"` } - _ = json.Unmarshal(raw.ToolInput, &toolInput) + if bytes.HasPrefix(bytes.TrimSpace(raw.ToolInput), []byte("{")) { + if err := json.Unmarshal(raw.ToolInput, &toolInput); err != nil { + return nil, err + } + } input := raw.HookInput if toolInput.FilePath != "" { diff --git a/app/cli/internal/trace/claude/hooks_test.go b/app/cli/internal/trace/claude/hooks_test.go index 8dc5a48de..3e5c37e81 100644 --- a/app/cli/internal/trace/claude/hooks_test.go +++ b/app/cli/internal/trace/claude/hooks_test.go @@ -404,6 +404,12 @@ func TestReadHookInput(t *testing.T) { assert.Empty(t, input.SessionID) }) + t.Run("an object tool input with a wrong field type is an error", func(t *testing.T) { + r := bytes.NewBufferString(`{"session_id":"s-1","hook_event_name":"PreToolUse","tool_name":"Write","tool_input":{"file_path":42}}`) + _, err := provider.ReadHookInput(r) + require.Error(t, err) + }) + t.Run("a tool input that is not an object gives an empty file path", func(t *testing.T) { r := bytes.NewBufferString(`{"session_id":"s-1","hook_event_name":"PreToolUse","tool_name":"Write","tool_input":"text"}`) input, err := provider.ReadHookInput(r) From a7cf6ef4677194fdfcf150a07eef3326b755b7bc Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Wed, 11 Nov 2026 02:28:21 +0100 Subject: [PATCH 16/16] docs: remove random date from CLI readme Assisted-by: GitHub Copilot Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 386938e5-0467-469a-81ef-4aae40023df7 --- app/cli/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/app/cli/README.md b/app/cli/README.md index ca7eef91a..e89f6b777 100644 --- a/app/cli/README.md +++ b/app/cli/README.md @@ -1,5 +1,3 @@ -Random date: 2024-07-19 - # Command Line Interface (CLI) This Command Line Interface (CLI) is a local client that's used for two purposes: