Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/cli/internal/trace/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ Which lines of a commit the AI wrote.
|---------|---------------|-------------|--------|--------------|------------|---|---|
| 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`. A session with no commit sends no evidence, so it reports no totals (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 |
Expand Down
4 changes: 0 additions & 4 deletions app/cli/internal/trace/attribution/enrich.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,6 @@ func Enrich(sessionID string, ledgers map[string]*state.AILineAttribution, commi
changes.HumanLinesAdded += f.HumanLinesAdded
changes.HumanLinesRemoved += f.HumanLinesRemoved
}

// All the lines that the agent edits of the session wrote, also the ones
// that never reached a commit (spec issue-3639, R-011, D-011).
changes.AIGeneratedLinesAdded, changes.AIGeneratedLinesRemoved = self.GeneratedAdded, self.GeneratedRemoved
}

// fileSplit is the AI/human split of the changed lines of one file.
Expand Down
55 changes: 0 additions & 55 deletions app/cli/internal/trace/attribution/enrich_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,61 +189,6 @@ func TestEnrich_Legacy(t *testing.T) {
})
}

func TestEnrich_GeneratedLines(t *testing.T) {
withGenerated := func(attr *state.AILineAttribution, added, removed int) *state.AILineAttribution {
attr.GeneratedAdded, attr.GeneratedRemoved = added, removed

return attr
}

testCases := []struct {
name string
ledgers map[string]*state.AILineAttribution
wantAdded, wantRemoved int
}{
{
// The agent wrote 10 lines and removed 3. Only 2 lines reached
// the commit; the session still reports all of them (spec
// issue-3639, D-011).
name: "reports all the lines of the agent edits, also the ones that no commit holds",
ledgers: map[string]*state.AILineAttribution{
testSession: withGenerated(ledger(testSession, testFile, []string{"a", "b"}, nil), 10, 3),
},
wantAdded: 10,
wantRemoved: 3,
},
{
name: "does not add the lines of another session",
ledgers: map[string]*state.AILineAttribution{
testSession: withGenerated(ledger(testSession, testFile, []string{"a", "b"}, nil), 2, 0),
otherSession: withGenerated(ledger(otherSession, testFile, []string{"c"}, nil), 7, 1),
},
wantAdded: 2,
},
{
name: "a session with no ledger reports no lines",
ledgers: nil,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
changes := &aicodingsession.CodeChanges{
LinesAdded: 2,
Files: []aicodingsession.FileChange{{Path: testFile, LinesAdded: 2}},
}
commits := []CommitLines{{SessionIDs: []string{testSession}, Files: []tracegit.FileLines{
{Path: testFile, Added: []string{"a", "b"}},
}}}

Enrich(testSession, tc.ledgers, commits, nil, changes)

assert.Equal(t, tc.wantAdded, changes.AIGeneratedLinesAdded)
assert.Equal(t, tc.wantRemoved, changes.AIGeneratedLinesRemoved)
})
}
}

func TestEnrich_Lines(t *testing.T) {
type split struct{ aiAdded, aiRemoved, humanAdded, humanRemoved int }

Expand Down
15 changes: 15 additions & 0 deletions app/cli/internal/trace/attribution/generated.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package attribution

import (
"github.com/chainloop-dev/chainloop/app/cli/internal/trace/state"
"github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials/aicodingsession"
)

Expand Down Expand Up @@ -47,3 +48,17 @@ func FilterGenerated(changes *aicodingsession.CodeChanges, isGenerated func(path
}
changes.Files = filtered
}

// SetAIGeneratedLines sets the lines that the agent edits of a session added
// and removed, also the ones that never reached a commit (spec issue-3639,
// R-011, D-011). As in FilterGenerated, the files that isGenerated matches do
// not count: a generator wrote them, not the agent. A nil ledger sets no
// lines, and a nil isGenerated leaves out no file.
func SetAIGeneratedLines(changes *aicodingsession.CodeChanges, ledger *state.AILineAttribution, isGenerated func(path string) bool) {
changes.AIGeneratedLinesAdded, changes.AIGeneratedLinesRemoved = 0, 0
if ledger == nil {
return
}

changes.AIGeneratedLinesAdded, changes.AIGeneratedLinesRemoved = ledger.GeneratedLines(isGenerated)
}
64 changes: 64 additions & 0 deletions app/cli/internal/trace/attribution/generated_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"testing"

tracegit "github.com/chainloop-dev/chainloop/app/cli/internal/trace/git"
"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"
Expand Down Expand Up @@ -144,6 +145,69 @@ func TestFilterGenerated(t *testing.T) {
})
}

func TestSetAIGeneratedLines(t *testing.T) {
const genFile = "cmd/wire_gen.go"
isGenerated := func(path string) bool { return path == genFile }

testCases := []struct {
name string
ledger *state.AILineAttribution
isGenerated func(string) bool
wantAdded, wantRemoved int
}{
{
// The agent wrote 10 lines and removed 3. Only some of them may
// reach a commit; the session still reports all of them (spec
// issue-3639, D-011).
name: "reports all the lines of the agent edits, also the ones that no commit holds",
ledger: &state.AILineAttribution{Generated: map[string]state.LineTotals{testFile: {Added: 10, Removed: 3}}},
isGenerated: isGenerated,
wantAdded: 10,
wantRemoved: 3,
},
{
// A shell command such as wire rewrote a generated file (PFM-8130).
name: "leaves out the lines of generated files",
ledger: &state.AILineAttribution{Generated: map[string]state.LineTotals{
testFile: {Added: 2, Removed: 1},
genFile: {Added: 1334405, Removed: 1638639},
}},
isGenerated: isGenerated,
wantAdded: 2,
wantRemoved: 1,
},
{
name: "a session that changed only generated files reports no lines",
ledger: &state.AILineAttribution{Generated: map[string]state.LineTotals{genFile: {Added: 5, Removed: 1}}},
isGenerated: isGenerated,
},
{
name: "a nil matcher leaves out no file",
ledger: &state.AILineAttribution{Generated: map[string]state.LineTotals{
testFile: {Added: 2},
genFile: {Added: 5, Removed: 1},
}},
wantAdded: 7,
wantRemoved: 1,
},
{
name: "a session with no ledger reports no lines",
isGenerated: isGenerated,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
changes := &aicodingsession.CodeChanges{AIGeneratedLinesAdded: 99, AIGeneratedLinesRemoved: 99}

SetAIGeneratedLines(changes, tc.ledger, tc.isGenerated)

assert.Equal(t, tc.wantAdded, changes.AIGeneratedLinesAdded)
assert.Equal(t, tc.wantRemoved, changes.AIGeneratedLinesRemoved)
})
}
}

func writeGitAttributes(t *testing.T, dir, content string) {
t.Helper()
path := filepath.Join(dir, ".gitattributes")
Expand Down
38 changes: 31 additions & 7 deletions app/cli/internal/trace/state/ailines.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,30 @@ type AILineAttribution struct {
// Legacy marks each file with an edit recorded before line fingerprints
// existed. Its attribution falls back to the recorded ranges.
Legacy map[string]bool `json:"-"`
// GeneratedAdded and GeneratedRemoved are the lines that all the agent
// edits of the session added and removed, also the ones that never
// reached a commit (R-011).
GeneratedAdded int `json:"-"`
GeneratedRemoved int `json:"-"`
// Generated holds, for each file, the lines that all the agent edits of
// the session added and removed, also the ones that never reached a
// commit (R-011).
Generated map[string]LineTotals `json:"-"`
}

// LineTotals is a number of added and removed lines.
type LineTotals struct {
Added, Removed int
}

// GeneratedLines returns the lines that all the agent edits of the session
// added and removed (R-011), except in the files that skip matches. A nil
// skip leaves out no file.
func (a *AILineAttribution) GeneratedLines(skip func(path string) bool) (added, removed int) {
for file, t := range a.Generated {
if skip != nil && skip(file) {
continue
}
added += t.Added
removed += t.Removed
}

return added, removed
}

// PendingEdit is an uncommitted edit to one file.
Expand All @@ -82,6 +101,7 @@ func newAILineAttribution(sessionID string) *AILineAttribution {
Erased: make(map[string]LineCounts),
Open: make(map[string]*OpenLines),
Legacy: make(map[string]bool),
Generated: make(map[string]LineTotals),
}
}

Expand Down Expand Up @@ -143,8 +163,12 @@ func (a *AILineAttribution) applyEdit(entry *aiLineEntry) {
}
}

a.GeneratedAdded += entry.LinesAdded
a.GeneratedRemoved += entry.LinesRemoved
if entry.LinesAdded != 0 || entry.LinesRemoved != 0 {
t := a.Generated[entry.File]
t.Added += entry.LinesAdded
t.Removed += entry.LinesRemoved
a.Generated[entry.File] = t
}
}

// aiLinesPath returns the path for a session's AI line attribution file (JSONL).
Expand Down
18 changes: 16 additions & 2 deletions app/cli/internal/trace/state/ailines_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,22 @@ func TestAILineAttribution_Lines(t *testing.T) {
require.NoError(t, store.SettleLines("sess", fileA, LineSet{Added: []string{"a", "b"}}))

attr := store.LoadAILineAttribution("sess")
assert.Equal(t, 6, attr.GeneratedAdded)
assert.Equal(t, 3, attr.GeneratedRemoved)
added, removed := attr.GeneratedLines(nil)
assert.Equal(t, 6, added)
assert.Equal(t, 3, removed)
assert.Equal(t, map[string]LineTotals{fileA: {Added: 2, Removed: 1}, "b.go": {Added: 4, Removed: 2}}, attr.Generated)
})

t.Run("generated line counts leave out the files that skip matches", func(t *testing.T) {
store := NewGitStore(t.TempDir())
require.NoError(t, store.RecordEdit("sess", fileA, EditRecord{AddedCount: 3, RemovedCount: 1, Lines: LineSet{}}))
require.NoError(t, store.RecordEdit("sess", "wire_gen.go", EditRecord{AddedCount: 5, RemovedCount: 1, Lines: LineSet{}}))
require.NoError(t, store.RecordEdit("sess", "wire_gen.go", EditRecord{AddedCount: 2, RemovedCount: 4, Lines: LineSet{}}))

attr := store.LoadAILineAttribution("sess")
added, removed := attr.GeneratedLines(func(path string) bool { return path == "wire_gen.go" })
assert.Equal(t, 3, added)
assert.Equal(t, 1, removed)
})

t.Run("an entry without fingerprints is legacy", func(t *testing.T) {
Expand Down
5 changes: 3 additions & 2 deletions app/cli/pkg/action/trace_codex_hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ func TestCodexMultiFilePatchAttribution(t *testing.T) {
assert.Contains(t, ledger.Open, "two.txt")
assert.Contains(t, ledger.Open, "gone.txt")
assert.Len(t, ledger.Open["gone.txt"].Removed, 1)
assert.Equal(t, 2, ledger.GeneratedAdded)
assert.Equal(t, 2, ledger.GeneratedRemoved)
added, removed := ledger.GeneratedLines(nil)
assert.Equal(t, 2, added)
assert.Equal(t, 2, removed)
// An unchanged human line must not become an AI addition.
assert.Len(t, ledger.Open["one.txt"].Added, 1)
session, err := store.LoadSessionRecord("codex-patch")
Expand Down
1 change: 1 addition & 0 deletions app/cli/pkg/action/trace_hook_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1101,6 +1101,7 @@ func sessionCodeChanges(gitClient tracegit.Client, repoRoot, sessionID string, c
}

attribution.Enrich(sessionID, ledgers, lines, tip, codeChanges)
attribution.SetAIGeneratedLines(codeChanges, ledgers[sessionID], isGenerated)

if !complete {
for i := range codeChanges.Files {
Expand Down
53 changes: 46 additions & 7 deletions app/cli/pkg/action/trace_line_attribution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,8 @@ func TestLineAttribution_ShellDoesNotRecordOpenLinesAgain(t *testing.T) {
attr := r.store.LoadAILineAttribution(lineSession)
assert.Equal(t, 3, attr.Written["a.go"].Len())
assert.Equal(t, 3, attr.Open["a.go"].Added.Len())
assert.Equal(t, 3, attr.GeneratedAdded)
added, _ := attr.GeneratedLines(nil)
assert.Equal(t, 3, added)

r.commit("feat: a", "a.go")
assert.Equal(t, lineSplit{aiAdded: 3}, fileSplitOf(t, r.sessionChanges(lineSession), "a.go"))
Expand Down Expand Up @@ -718,7 +719,8 @@ func TestLineAttribution_ShellCommandWithSeveralCommits(t *testing.T) {
attr := r.store.LoadAILineAttribution(lineSession)
assert.Equal(t, 3, attr.Written["a.go"].Len())
assert.Equal(t, 1, attr.Written["b.go"].Len())
assert.Equal(t, 4, attr.GeneratedAdded)
added, _ := attr.GeneratedLines(nil)
assert.Equal(t, 4, added)
}

// A pre hook whose HEAD commits were lost (the heads file is missing or
Expand Down Expand Up @@ -746,7 +748,8 @@ func TestLineAttribution_ShellLostHeadsIsNotAHeadMove(t *testing.T) {

attr := r.store.LoadAILineAttribution(lineSession)
assert.Contains(t, attr.Files, "a.go")
assert.Equal(t, 0, attr.GeneratedAdded)
added, _ := attr.GeneratedLines(nil)
assert.Equal(t, 0, added)
}

// wireGenFile is a file that a code generator rewrites.
Expand Down Expand Up @@ -877,8 +880,9 @@ func TestLineAttribution_ShellHeadMoveRecordsNoUpstreamLines(t *testing.T) {
tc.run(t, r)

attr := r.store.LoadAILineAttribution(lineSession)
assert.Equal(t, tc.wantAdded, attr.GeneratedAdded, "generated lines added")
assert.Equal(t, tc.wantRemoved, attr.GeneratedRemoved, "generated lines removed")
added, removed := attr.GeneratedLines(nil)
assert.Equal(t, tc.wantAdded, added, "generated lines added")
assert.Equal(t, tc.wantRemoved, removed, "generated lines removed")
files := make([]string, 0, len(attr.Files))
for f := range attr.Files {
files = append(files, f)
Expand All @@ -899,6 +903,41 @@ func TestLineAttribution_GeneratedLines(t *testing.T) {
require.NoError(t, os.Remove(filepath.Join(r.dir, "scratch.go")))

attr := r.store.LoadAILineAttribution(lineSession)
assert.Equal(t, 4, attr.GeneratedAdded)
assert.Equal(t, 2, attr.GeneratedRemoved)
added, removed := attr.GeneratedLines(nil)
assert.Equal(t, 4, added)
assert.Equal(t, 2, removed)
}

// A generator that the agent runs, such as wire, writes a generated file. Its
// lines are not in the files of the evidence, and they do not count in the
// AI-generated lines either (PFM-8130).
func TestSessionCodeChanges_GeneratedFilesDoNotCountAsAIGenerated(t *testing.T) {
r := newLineRepo(t)
r.humanWrite(".gitattributes", wireGenFile+" linguist-generated=true\n")
r.humanWrite(wireGenFile, "package main\n")
runGit(t, r.dir, "add", ".gitattributes", wireGenFile)
runGit(t, r.dir, "commit", "-q", "-m", "chore: attributes")

r.agentWrite(lineSession, "a.go", "one\ntwo\n")
r.shellWrite(lineSession, func() {
r.humanWrite(wireGenFile, "package main\n\nfunc a() {}\nfunc b() {}\n")
})
r.commit("feat: a", "a.go", wireGenFile)

// The ledger holds the lines of both files: the shell command wrote them.
all, _ := r.store.LoadAILineAttribution(lineSession).GeneratedLines(nil)
require.Equal(t, 5, all)

records, err := r.store.LoadAllCommitRecords()
require.NoError(t, err)
commits := sessionCommitGroups(records, nil, false)[lineSession]
require.Len(t, commits, 1)

client := tracegit.NewGitClient()
cc := sessionCodeChanges(client, r.dir, lineSession, commits, loadLedgers(r.store, zerolog.Nop()), newLineCache(client, r.dir, zerolog.Nop()), client.GeneratedMatcher(r.dir), zerolog.Nop())
require.NotNil(t, cc)
require.Len(t, cc.Files, 1)
assert.Equal(t, "a.go", cc.Files[0].Path)
assert.Equal(t, 2, cc.AIGeneratedLinesAdded)
assert.Equal(t, 0, cc.AIGeneratedLinesRemoved)
}
Loading